自调用函数中没有var关键字的变量如何工作?

时间:2016-06-28 11:19:07

标签: javascript

var salary = "1000$";

(function () {
    console.log("Original salary was " + salary); //1000$

    salary = "5000$";

    console.log("My New Salary " + salary); //5000$
})();

(function () {
    console.log("Original salary was " + salary); //undefined ?? 

    var salary = "5000$";

    console.log("My New Salary " + salary); //5000$
})();

为什么以及第一和第三个控制台日志显示不同的输出?

2 个答案:

答案 0 :(得分:2)

这是由于变量托管。在你的第二个IIFE函数中,你已经声明了工资变量,它实际上移到了函数的顶部并且掩盖了你的全局薪水函数

javascript将此代码转换为.see代码。

  var salary = "1000$";

    (function () {
        console.log("Original salary was " + salary); //1000$

        salary = "5000$";

        console.log("My New Salary " + salary); //5000$
    })();

    (function () {
        var salary ;
        console.log("Original salary was " + salary); //undefined ?? 

        // get move to opvar salary = "5000$";

       salary = "5000$";

        console.log("My New Salary " + salary); //5000$
    })();

答案 1 :(得分:1)

第一行创建一个名为salary的全局变量。在第二个函数的范围内,有一个名为salary的局部变量。这意味着在第二个函数中你不能以这种方式访问​​全局变量,并且尚未设置局部变量,所以它实际上是未定义的,直到设置它的行。