Javascript 提升自执行功能

Javascript Hoisting on self executing function

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
//// 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

需要记住的重要事项

  1. 任何使用 var 声明的变量在控件到达定义它的行之前将是 undefined,除非分配了其他内容。这是因为,在JavaScript、declarations are hoisted.

  2. 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。这就是为什么您分别得到 undefined10

最后一节

console.log(d, 4);

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

你有 undefined 2 的原因是因为这个函数中有 var d = 10

这意味着这个变量将在相同的范围内声明,但稍后。

P.S:如果你想到处输出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