2
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

谁能解释一下这段代码是如何产生注释输出的?

4

4 回答 4

3

要记住的重要事项

  1. 用 , 声明的任何变量var都将undefined在控件到达定义它的行之前,除非分配了其他东西。这是因为,在 JavaScript 中,声明是提升的

  2. 用 , 声明的任何变量var都将作用于定义它的函数。


有了这个理解,让我们看一下代码。

第一节

console.log(d, 1);
var d = 8;

d在执行声明的行之前访问d。所以,dundefined

中段

(function() {
  console.log(d, 2);
  var d = 10;
  console.log(d, 3);
})();

这里也一样。您在实际声明d之前和之后访问。d这就是为什么你得到undefined10分别。

最后一节

console.log(d, 4);

由于在函数内声明的变量在函数外不可用,因此在这一行d中将与在第 2 行声明的变量相同。最后分配的值为 8。

于 2016-01-09T12:54:19.737 回答
2

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

于 2016-01-09T12:54:11.863 回答
0

您拥有的原因undefined 2是因为拥有var d = 10此功能。

这意味着该变量将在同一范围内声明,但稍后声明。

PS:如果要8 ...到处输出,只要去掉这个内层var d = 10就可以了。

于 2016-01-09T12:56:58.273 回答
0

因为这就是代码对引擎的样子:

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
于 2016-01-09T13:53:54.017 回答