我试图解释 javascript 提升的问题,但我无法解释 b
的情况。
b = 50
不是修改了全局变量b
吗?
是 block 级作用域的原因吗?
环境
Chrome 77
{
a = 50
function a() {}
}
console.log(a) // 50
console.log(b) // undefined
{
console.log(b) // f b () {}
function b() {}
b = 50
console.log(b) // 50
}
console.log(b) // ƒ b () {}
我以为 b
和 a
一样是 50。但它是一个函数。
最佳答案
这里发生了两件重要的事情
- 托管发生在一个函数中 - 将任何东西放在 {} 中被视为一个 block ,而不是一个函数。
- 函数声明被提升到变量之上 - 因此如果 var 和函数具有相同的名称,函数将获得优先权
console.log(x); // f() {} //hoisted with assignment since "x" is function
var x = 90;
function x() {}
console.log(a); // undefined // hoisting of child block-scope variable is never assigned not even if "a" is function
{
console.log(a); // f(){}
a = 50; //**while execution //since global scope "a" not assigned yet it takes the first assignment in this child-block
console.log(a); // 50 // because value has been assigned to "a" already
function a(){} // Ignored //function "a" was never hoisted over variable assignment
console.log(a); // 50 // block scope has "a=50" attached to it
}
console.log(a); // 50 // global scope also has "a=50" attached to it
console.log(b) // undefined // hoisting of child block-scope variable is never assigned not even if "a" is function
{
console.log(b) // f () {}
function b() {} // While hoisting global scope and this block scope get "b" attached to their scope as a function
b = 50 // var b is reassigned, but "b" attached to this block is only reassigned, since type is changed globally attached "b" is not reached
console.log(b) // 50
}
console.log(b) // ƒ () {} // globally attached "b" is a function
关于javascript - 如何解释下面的例子?吊装?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58160871/