在函数内部使用的全局变量如果语句似乎是空白的JavaScript

时间:2016-12-27 05:02:32

标签: javascript scope

我很好奇为什么变量在被定义为全局变量时被认为是空白的。

var name = "Richard";
function showName(){
    if(name){   // the name is already defined as global variable but why the condition is false ?
        var name="Jack";
        console.log(name);
    }

}
showName()  // its blank
console.log(name); //display Richard

如果我将if(name)的陈述更改为if(!name),那么它会按预期工作。为什么"名称"返回空白,因为它已经有一个用值定义的全局变量。

我只是想了解JavaScript。我正在学习它。

1 个答案:

答案 0 :(得分:4)

这是因为您已将name声明为函数的局部变量,shadowing为全局name变量。

在闭包中用var声明变量的任何地方,它都会根据名称创建和hoists一个局部变量,初始值为undefined(假值,所以如果块没有运行。)

删除var中的var name="Jack";,您只需要var来声明变量,而不是重新分配变量。



var name = "Richard";
function showName(){
    if(name){
        name="Jack";
        console.log(name);
    }

}
showName()
console.log(name);