gpt4 book ai didi

JavaScript:是否提升了属性函数?

转载 作者:行者123 更新时间:2023-11-30 09:22:38 25 4
gpt4 key购买 nike

我试图理解为什么以下代码有效:

function checkReading () {
if (checkReading.read) {
return;
}
checkReading.read = this.scrollHeight - this.scrollTop === this.clientHeight;
document.registration.accept.disabled = document.getElementById("nextstep").disabled = !checkReading.read;
checkReading.noticeBox.innerHTML = checkReading.read ? "Thank you." : "Please, scroll and read the following text.";
}

Source: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight

我挣扎的部分是如何 if(checkReading.read)可以在 checkReading.read 之前调用属性在 checkReading 上声明函数对象。

即使函数声明直接作为属性(如上)完成,也被提升到其作用域的顶部,这是有效的原因吗?

所以在 JS 引擎完成事件循环的第一个 tick 之后,checkReading.read实际上被提升(移动)到 checkReading 的顶部功能?

PS:我知道正常的函数声明被提升了function foo() {..}到他们范围的顶部,但不确定这是否也适用于上述属性。

最佳答案

The part I am struggling with is how if(checkReading.read) can be called before the checkReading.read property is declared on the checkReading function object.

这与函数或提升无关。您可以访问任何对象上不存在的属性:

var foo = {};
console.log(foo.bar);

如果该属性不存在,其返回值为undefined,强制转换为false

I actually thought about the falsy concept, but then the below code would never be reached. Or am I missing something?

如果条件为false,则if语句的主体执行,即return; 没有被执行,因此函数的其余部分被执行。

关于JavaScript:是否提升了属性函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50594255/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com