{function foo(){};foo=1;function foo(){};foo=2;}
console.log(foo); // 1
谁能解释一下为什么这里输出“1”?
Edit:
似乎存在实现差异,在“Chrome”、“Firefox”、“Nodejs”中输出为“1”,但在“Safari”中输出为“2”
让我们美化该块并将其分解:
{
function foo() {};
foo = 1;
function foo() {};
foo = 2;
}
console.log(foo); // 1
块作用域函数声明通常将其变量名称提升到其块之外(其值为undefined
),但仅在块内部接收一次值。您可以查看有关该行为的更多详细信息here https://stackoverflow.com/questions/31419897/what-are-the-precise-semantics-of-block-level-functions-in-es6.
但这种情况有点不同——你声明了一个函数twice在一个块中。看起来像第一个foo
函数被分配给块外部可见的名称。如果您将属性描述符记录在window
在代码中的不同点。
看起来,一旦达到重复的函数声明,就会进一步引用foo
块内的变量名称引用绑定仅在块内。所以foo = 2
在底部,因为它位于重复声明之后,所以只会导致2
值绑定到foo
在块内引用时的名称。块外的值仍然是块内的值foo
最后举行before重复的函数声明:
// Variable name is hoisted: it exists on the global object, but is undefined
console.log(Object.getOwnPropertyDescriptor(window, 'foo'));
{
// Function declaration: global foo gets assigned to
function foo() {};
console.log(window.foo);
// Assignment to foo name: global foo gets assigned to
foo = 1;
// Assignment to foo name: global foo gets assigned to
foo = 3;
console.log(window.foo);
// Duplicate function declaration: past this point, foo now no longer refers to the global foo
// but to a locally-scoped identifier
function foo() {};
// See how the window value remains at 3:
console.log(window.foo);
// So this assignemnt only changes the binding of the `foo` inside this block
// while window.foo remains at 3:
foo = 2;
}
console.log(foo); // 3
查看原始代码的另一种方式:
{
function foo() {}; // this ALSO does: window.foo = function foo() {};
foo = 1; // this ALSO does: window.foo = 1
function foo() {}; // this actually does: fooLocal = function foo() {};
// further references to "foo" in this block refer to fooLocal
foo = 2; // this actually does: fooLocal = 2
}
console.log(foo); // references window.foo
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)