具有相同变量名称的内部函数提升

mav*_*ick 7 javascript

所以我以为我理解了JavaScript的提升,直到看到如下内容:

function hoist(a) {
    console.log(a);
    var a = 10;
}

hoist(5);
Run Code Online (Sandbox Code Playgroud)

上面的代码输出5,不是undefined!根据我的理解,该函数在解释器中看起来像这样:

function hoist(a) {
    var a;  // This should overshadow the parameter 'a' and 'undefined' should be assigned to it
    console.log(a);  // so this should print undefined
    a = 10;  // now a is assigned 10
}
Run Code Online (Sandbox Code Playgroud)

那么这是怎么回事?

I w*_*ce. 6

如果var被调用了b,那将是正确的,但是var a已经存在。重新声明已经存在的javascript变量不会执行任何操作。它不会将值更改为undefined。试试吧。

function hoist(a) {
    var a; // no op, does not change a to  undefined.
    console.log(a);
    a = 10;
}

hoist(18);
Run Code Online (Sandbox Code Playgroud)