【问题标题】:Variable Hoisting in JS [duplicate]JS中的变量提升[重复]
【发布时间】:2020-07-08 07:02:32
【问题描述】:

我对可变提升概念有点困惑。为什么第一个console.log(flag) 输出undefined?它不应该抓住已经初始化的 false 值向上移动范围链吗?

var flag = false;
(function(){
    console.log(flag);
    var flag = true; // JavaScript only hoists declarations, not initialisations

    console.log(flag);

    if(flag){
        let name = "John";
        const age = "24";

        console.log(name);
        console.log(age);
    }

    //console.log(name); //ReferenceError: name is not defined ( as name is block scoped here )
    //console.log(age);  //ReferenceError: age is not defined ( as age is block scoped )

})();

【问题讨论】:

标签: javascript


【解决方案1】:

在 JS 中,我们也有函数作用域,由于两个作用域中的变量名相同,全局 flag 被覆盖,因此第一个 console.log(flag) 输出未定义。考虑到这段代码:

(function(){
console.log(flag);
var flag = true;
})

应用变量提升概念,这将在内部变成这样:

(function(){
var flag=undefined;
console.log(flag);
flag = true;
})

您会因为外部范围 flag 变量而感到困惑,但由于使用了相同的命名约定,它将被功能范围 flag 变量覆盖。

【讨论】:

    【解决方案2】:

    flag 托管在 IIFE

    var flag = false;
    (function(){
        var flag; // undefined
        console.log(flag);
        flag = true; // JavaScript only hoists declarations, not initializations
    
        console.log(flag);
    
        if(flag){
            let name = "John";
            const age = "24";
    
            console.log(name);
            console.log(age);
        }
    
        //console.log(name); //ReferenceError: name is not defined ( as name is block scoped here )
        //console.log(age);  //ReferenceError: age is not defined ( as age is block scoped )
    
    })();
    

    【讨论】:

    • 因为flag在第一个日志中的值是undefined。如果要打印false,则应删除第二个var flag = 声明并保留flag =
    • 哦,这是因为只有我的标志声明被提升到函数顶部。
    【解决方案3】:

    以下情况发生:

    您的声明 var flag = true; 在其执行环境中被提升。在这种情况下,这是您的功能。它有点奇怪,但只有声明的变量在没有赋值的情况下被提升。

    var flag = false;
    (function(){
        console.log(flag);
        var flag = true; // JavaScript only hoists declarations, not initializations
    
        console.log(flag);
    
        if(flag){
            let name = "John";
            const age = "24";
    
            console.log(name);
            console.log(age);
        }
    
        //console.log(name); //ReferenceError: name is not defined ( as name is block scoped here )
        //console.log(age);  //ReferenceError: age is not defined ( as age is block scoped )
    
    })();

    【讨论】:

    • 非常感谢您解惑。
    猜你喜欢
    • 2016-01-14
    • 2018-06-10
    • 2019-05-07
    • 2018-11-05
    • 1970-01-01
    • 2015-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多