所以,我试图在javascript中掌握范围链的概念,因此我创建了以下示例来检查我是否正确。
注意:我熟悉以下概念(执行上下文和词法环境)。
示例:
function test(){
function test2(){
//This prints 2 as expected
console.log(a);
}
//This should print 1 but instead it prints undefined
console.log(a);
var a = 2;
test2();
}
var a = 1;
test();
如果我评论以下内容:
//var a = 2;
然后两种情况下的输出都是1.
答案 0 :(得分:1)
您应该在JavaScript中查看Hoisting Concept。 在进入执行步骤之前,JS引擎会将所有声明移到块的顶部。
关于你的例子:
function test(){
function test2(){
//This prints 2 as expected
console.log(a);
}
//This should print 1 but instead it prints undefined
console.log(a);
var a = 2;
test2();
}
var a = 1;
test();
会像这样对待
var a; // initialized to undefined
function test(){
var a; // initialized to undefined [which is printed]
function test2(){
//This prints 2 as expected
console.log(a);
}
//This will print undefined which is the actual value of a
console.log(a);
a = 2;
test2();
}
a = 1;
test();
这就是打印未定义的原因