gpt4 book ai didi

javascript - javascript this 又让我困惑了

转载 作者:行者123 更新时间:2023-11-28 03:40:49 25 4
gpt4 key购买 nike

一些更新:感谢大家的帮助。我想这可能是关键的混淆点:参数区域中的“this”不被视为函数“内部”,因此不会遵循 mdn 指定的规则(this 指向调用该方法的 obj)。下面的例子:

someObj {
someF(//but if "this" shows up here, it doesn't point to someObj) {
//when called, "this" here will point to someObj
}
}

原问题:

读了很多文档后,我以为我对此有了很好的理解,但我错了。

下面的例子来自MDN :

function Counter() {
this.sum = 0;
this.count = 0;
}
Counter.prototype.add = function(array) {
// Here "this" points to obj
array.forEach(function(entry) {
this.sum += entry;
++this.count;
}, this);
// ^---- Note, why it points to obj, not array [2,5,9]???

// Here "this" points to obj
};

const obj = new Counter();
obj.add([2, 5, 9]);
obj.count;
// 3
obj.sum;
// 16

我明白了:

  • 需要将 this 传递给 forEach,否则在回调函数中,this 将指向全局/窗口(非严格模式)。
  • function(array) 的大部分区域中,this 指向 obj(从 new Counter() 创建),如评论。
  • 回调函数如何使用从 forEach 传递的“this”作为第二个参数。我对此没有任何疑问

但是基于这个article on MDN具体来说:

"As an object method, when a function is called as a method of an object, its this is set to the object the method is called on."

传入回调的 this (由 ^---Note 突出显示)不应该指向数组对象,即本例中的 [2,5,9] 吗?为什么它会指向 obj 而不是数组?

非常感谢您的帮助,实在是太令人困惑了。

最佳答案

the needs to pass in "this" in forEach, otherwise "this" in internal function would point to global/window (non-strict mode).

this 的值取决于函数的调用方式。您看不到调用传递给 forEach 的回调函数的代码(它是浏览器内部的)。碰巧,它确实这样调用它,所以它是 window (如果您不向 forEach 传递第二个参数)。

As an object method, when a function is called as a method of an object, its this is set to the object the method is called on

这无关紧要。您没有将回调函数作为对象的方法来调用。您将其传递给 forEach ...然后 forEach 调用它。

正在调用forEach作为数组的方法,因此forEach函数内 - 您看不到,因为它是浏览器内部的 - this 将是数组。

Why it would point to obj instead of the array?

因为 forEach 被明确设计为以这样的方式调用回调函数:forEach 的第二个参数是回调函数。

您引用了这样说的文档。

关于javascript - javascript this 又让我困惑了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57316921/

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