做用域、做用域链是JavaScript中重要的组成部分和重点知识,是咱们务必要掌握的内容。javascript
若是没有掌握,那么做为重点难点之一的函数的闭包将会难以理解、无从下手。java
规则:git
var scope = 'global';
function f() {
console.log(scope); // 'global'
}
f();
复制代码
function f2() {
var scope2 = 'local2';
}
console.log(scope2); // 报错scope2 is not defined
复制代码
var scope3 = 'global3';
function f3() {
console.log(scope3); // undefined
var scope3 = 'local3';
console.log(scope3); // 'local3'
}
f3();
复制代码
// 1 if代码块
var scope = 'g';
if(true) {
var scope = 'l';
console.log(scope); // 'l'
}
console.log(scope); // 'l'
// 2 for代码块
for(var i = 0; i < 10; i++) {
console.log(i); // 0 1 2 3 4 5 6 7 8 9
}
// 3 function函数
function fn() {
aa = 5;
}
fn();
console.log(aa); // 5
复制代码
执行环境(execution context),也就是执行期上下文,它定义了执行期间能够访问的变量和函数。github
var g = 'g';
function fa() {
var a = 'a';
function fb() {
var b = 'b';
}
fb();
}
fa();
复制代码
解析:数据结构
var name = 1;
var person = {name: 'Nancy'};
with (person) {
console.log(name); // 'Nancy'
}
var person2 = {
name2: 'Mike',
age: 18,
height: 175,
wife: {
name2: 'AA',
age: 21
}
}
with (person2.wife) {
console.log(name2); // 'AA'
console.log(age); // 21
}
复制代码
function outer() {
var scope = 'outer';
function inner() {
return scope;
}
return inner;
}
var fn = outer();
console.log(fn()); // 'outer'
复制代码