javascript函数吊装内部语句

问题描述

{function foo(){};foo=1;function foo(){};foo=2;}
console.log(foo); // 1

有人可以解释为什么在这里输出“ 1”吗?

修改: 似乎存在实现差异,在“ Chrome”,“ Firefox”,“ Nodejs”中,输出为“ 1”,但在“ Safari”中,输出为“ 2”

解决方法

让我们美化这个区块并将其分解:

{
  function foo() {};
  foo = 1;

  function foo() {};
  foo = 2;
}
console.log(foo); // 1

块范围函数声明通常将其变量名悬挂在其块外(值为undefined),但仅在块内接收到一个值。您可以查看有关该行为here的更多详细信息。

但是这种情况有些不同-您在一个块中声明一个函数两次。看起来第一个foo函数已分配给在块外部可见的名称。如果您将属性描述符记录在代码中不同位置的window上,则会看到此信息。

看起来,一旦达到重复的函数声明,对块内foo变量名的进一步引用就仅在块内引用绑定 。因此,底部的foo = 2由于在重复声明之后,因此在块中引用2时,只会导致foo的值绑定到foo的名称上。块外的值仍然是// 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

查看原始代码的另一种方法:

wav