是的,我知道,回调到元素的值内jQuery的$.each
套this
。但这不是Array#forEach
的工作原理。相反,通常不会设置this
,除非指定了第二个thisArg
参数。
number=[1,2,3,4,5];
Array.prototype.forEach.call(number, function(elem) {
console.log(elem);
^^^^ Access element via parameter, not `this`
});
如果由于某种原因,你通过一些this
步入回调,然后将其指定为另一个参数forEach
,在其他的答案中提到这一点很重要。这this
将在每个调用回调相同;它与当前的迭代无关。
Array.prototype.forEach.call(
number,
function(elem) {
console.log("Inside callback, this is", this); // 42
console.log(elem);
},
42);
使用thisArg
并不常见。
obj = {
vals: [1, 2, 3],
message: "the value is",
alert(x) { alert(this.message + x); },
alertVals() { this.vals.forEach(this.alert, this); }
};
obj.alertVals();
这是一种替代方法之一
alertVals() { vals.forEach(this.alert.bind(this)); }
alertVals() { vals.forEach(elt => this.alert(elt)); }
你期望'this'是回调中:通常情况下,如果一个对象的方法被作为回调传递,但它使用?您将用于回调的'thisArg'与'forEach'的调用相混淆。 – 2016-11-13 07:49:48