gpt4 book ai didi

javascript - 匿名闭包函数中的“this”

转载 作者:行者123 更新时间:2023-11-29 17:17:18 25 4
gpt4 key购买 nike

(function(value) {
this.value = value;
$('.some-elements').each(function(elt){
elt.innerHTML = this.value; // possibly undefined (Why?)
});
})(2);

有人可以解释一下上面代码中“this”的值吗?

我的理解:

this.value = value//Line 2 - 这里 this 指的是全局对象elt.innerHTML = this.value;//第 4 行 - 为什么这“可能”未定义。请解释。

编辑:顺便说一句,我已经彻底阅读了这个(How does the "this" keyword work?)帖子中“这个”的解释(从我得到上面的代码的地方)

最佳答案

在作为回调发送到 .each() 的函数中方法,this 指的是 DOM 元素(对于包装在 jQuery 对象中的这个集合中的每个元素),而不是 window:

More importantly, the callback is fired in the context of the current DOM element, so the keyword this refers to the element.

(顺便说一句,这使得 elt arg 有点多余;至少,有点不清楚为什么要同时使用 thiselt 指代相同的东西)

但并非所有 DOM 元素都定义了 value 属性:公平地说,它只为元素的一个子集设置:inputselecttextareaoption 等。这可能就是您得到 undefined 结果的原因。

您可以使用 jQuery.proxy() 轻松调整它方法:

$('.some-elements').each($.proxy(function(elt){
elt.innerHTML = this.value;
}, this));

现在发送到 .each() 的函数使用外部 this 作为它的上下文(显然,它不再指向 DOM 元素,因为 elt 确实如此)。

关于javascript - 匿名闭包函数中的“this”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16305055/

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