Javascript在自执行功能上提升

时间:2016-01-09 12:50:28

标签: javascript closures hoisting 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

有人可以解释这段代码如何产生评论输出吗?

4 个答案:

答案 0 :(得分:3)

要记住的重要事项

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

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

  3. 通过这种理解,让我们看一下代码。

    第一部分

    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。

答案 1 :(得分: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

答案 2 :(得分:0)

您拥有undefined 2的原因是因为此函数中包含var d = 10

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

P.S:如果您想在任何地方输出8 ...,只需移除此内部var d = 10,您就会看到。

答案 3 :(得分: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