为什么第二个console.log()给出2,insted为1?

时间:2018-04-17 22:08:25

标签: javascript

为什么第二个console.log()2提供1的内容?



function f() {
    console.log(2);
}

f();

(function() {
    f();
    f = function() {
        console.log(1);
    }
})();




4 个答案:

答案 0 :(得分:3)

在javascript函数中,声明在封闭范围内提升,但赋值不是。第二次调用中的内容不是函数声明 - 您只是更改现有变量的值。如果您想在第二次通话中提升f(),则需要执行以下操作:

function f() {
    console.log(2);
}

f();

(function() {
    f();
    function f() { 
       // this is a function declaration so it will be hoisted to the top
       console.log(1);
    }
})();

答案 1 :(得分:1)

你正在调用f();在函数表达式之前的IIFE中。如果你移动你的第二个f();在表达式下方调用,您将得到您期望的结果。

function f() {
    console.log(2);
}

f();

(function() {
    f = function() {
        console.log(1);
    }
    f();
})();

答案 2 :(得分:1)

第二个“console.log(1)”输出2,因为它实际上是你要调用的第一个“console.log(2)” - 两次。你实际上从未调用过触发“console.log(1)”的函数。这是一个更具代表性的例子:

function f(value) {
    console.log(value);
}

f('a');

(function() {
    f('b');
    f = function() {
        console.log('c');
    }
    // unless you call "f()" at this point, this would not work. The "f = func ... " doesn't get hoisted.
})();

注意输出是“a”和“b”,但是从不记录“c”。函数的变量赋值不会被提升,我假设你会想到会发生什么?

希望有所帮助。

答案 3 :(得分:0)

这是因为函数声明正在执行两次。

FYI - 函数声明被提升但函数表达式没有。

function f() { // function declaration
  console.log(2);
}

f(); // 2

(function() {
  f(); // 2

  f = function() { // function expression
    console.log(1);
  }

  // you can use function expression here now that it is defined
  f(); // 1

})();

// will output:
// 2
// 2
// 1

阅读: