console.log(d, 1); // undefined 1
var d = 8;
(function() {
console.log(d, 2); // undefined 2
var d = 10
console.log(d, 3); // 10 3
})();
console.log(d, 4); // 8 4
谁能解释一下这段代码是如何产生注释输出的?
console.log(d, 1); // undefined 1
var d = 8;
(function() {
console.log(d, 2); // undefined 2
var d = 10
console.log(d, 3); // 10 3
})();
console.log(d, 4); // 8 4
谁能解释一下这段代码是如何产生注释输出的?
要记住的重要事项
用 , 声明的任何变量var
都将undefined
在控件到达定义它的行之前,除非分配了其他东西。这是因为,在 JavaScript 中,声明是提升的。
用 , 声明的任何变量var
都将作用于定义它的函数。
有了这个理解,让我们看一下代码。
第一节
console.log(d, 1);
var d = 8;
您d
在执行声明的行之前访问d
。所以,d
会undefined
。
中段
(function() {
console.log(d, 2);
var d = 10;
console.log(d, 3);
})();
这里也一样。您在实际声明d
之前和之后访问。d
这就是为什么你得到undefined
和10
分别。
最后一节
console.log(d, 4);
由于在函数内声明的变量在函数外不可用,因此在这一行d
中将与在第 2 行声明的变量相同。最后分配的值为 8。
console.log(d, 1); // undefined 1
//// d was not set yet, it has no value, wich is undefined
var d = 8;
(function() {
console.log(d, 2); // undefined 2
//// this function does not use the global scope, so there is no variable d set yet
var d = 10
console.log(d, 3); // 10 3
//// now you the local variable d to 10
})();
console.log(d, 4); // 8 4
//// this gives the global variable from above (value 8) as you did not change it with the self executing function
您拥有的原因undefined 2
是因为拥有var d = 10
此功能。
这意味着该变量将在同一范围内声明,但稍后声明。
PS:如果要8 ...
到处输出,只要去掉这个内层var d = 10
就可以了。
因为这就是代码对引擎的样子:
var outer_d;
console.log(outer_d, 1); // undefined 1
outer_d = 8;
(function() {
var inner_d;
console.log(inner_d, 2); // undefined 2
inner_d = 10
console.log(inner_d, 3); // 10 3
})();
console.log(outer_d, 4); // 8 4