JS 提升如何与块语句一起使用? [英] How JS hoisting works with block statement?
问题描述
在下面的这段代码中,我只想了解为什么 console.log(abc in this);
是 print true ,但在下一行 console.log(abc);
获取 undefined
In this following snipet, I just want to understand why console.log(abc in this);
is print true , but in next line console.log(abc);
getting undefined
console.log(this.abc);//undefined
console.log(abc in this);//true
console.log(abc);//undefined
{
function abc(){
console.log("hello");
}
}
console.log(abc); //ƒ abc(){console.log("hello");
你们中的任何人都可以解释一下在这种情况下提升和块语句是如何工作的吗?
Could anyone of you explain how Hoisting and Block statement working in this case?
推荐答案
在草率模式下,this
指的是全局对象.像这样的普通 非函数 块内的函数会将其变量名提升到 外部 作用域,但实际的函数不会分配给外部变量(以window 属性)直到内部块被执行.
In sloppy mode, this
refers to the global object. A function inside a plain non-function block like that will have its variable name hoisted to the outer scope, but the actual function will not be assigned to the outer variable (to the window property) until the inner block is executed.
详情请看这里:
正如在另一个问题中所解释的,对于解释器,您的代码如下所示:
As explained in that other question, to the interpreter, your code looks something like this:
window.abc = undefined; // top-level hoisting assigns to window properties
console.log(window.abc); // undefined
console.log(window.abc in window); // true
console.log(window.abc); // undefined
{
var _abc = function abc() {
console.log("hello");
};
window.abc = _abc;
}
console.log(window.abc); //ƒ abc(){console.log("hello");
之所以abc in this
为真,是因为abc
已经被初始化为window对象的一个属性,但是还没有尚未赋值.这类似于这里发生的事情:
The reason abc in this
is true is because abc
has been initialized as a property of the window object, but it hasn't been assigned a value yet. It's similar to what's happening here:
const obj = { foo: undefined };
console.log('foo' in obj);
这篇关于JS 提升如何与块语句一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!