首页 > 解决方案 > 在具有相同变量名的函数内部提升

问题描述

所以我以为我理解了 JavaScript 中的提升,直到我看到这样的东西:

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

hoist(5);

上面的代码输出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
}

那么这里发生了什么?

标签: javascript

解决方案


如果 var 被调用,你会是对的b,但 vara已经存在。重新声明一个已经存在的 javascript 变量不会做任何事情。它不会将值更改为未定义。尝试一下。

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

hoist(18);


推荐阅读