var a;
if (true) {
a = 5;
function a() {}
a = 0;
console.log(a)
}
console.log(a)Run Code Online (Sandbox Code Playgroud)
我看到了上面的代码,在{}中声明了一个函数。我认为它会打印0 0,但它会打印0 5
发生以下情况:
(1)存在两个变量声明a,一个在块内,一个在块外。
(2)函数声明被提升,并绑定到内部块变量。
a = 5到达(3),它将覆盖block变量。
(4)到达函数声明,并将块变量复制到外部变量。现在两个都是5。
a = 0达到(5),它将覆盖block变量。外部变量不受此影响。
var a¹;
if (true) {
function a²() {} // hoisted
a² = 5;
a¹ = a²; // at the location of the declaration, the variable leaves the block
a² = 0;
console.log(a²)
}
console.log(a¹);
Run Code Online (Sandbox Code Playgroud)
实际上,这实际上并不是规范的一部分,它是Web遗留兼容性语义的一部分,因此不要在块内声明函数,也不要依赖此代码以这种方式运行。
这也在这里解释
| 归档时间: |
|
| 查看次数: |
287 次 |
| 最近记录: |