是的,我知道,回調到元素的值內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