Yes, I know that jQuery's $.each sets this inside the callback to the value of the element. But that's not how Array#forEach works. Instead, this is usually not set, unless the second thisArg parameter is specified.
number=[1,2,3,4,5];
Array.prototype.forEach.call(number, function(elem) {
console.log(elem);
^^^^ Access element via parameter, not `this`
});
If for some reason it is important that you pass some this into the callback, then specify it as another parameter to forEach, as mentioned in other answers. This this will be the same on each invocation of the callback; it has nothing to do with the current iteration.
Array.prototype.forEach.call(
number,
function(elem) {
console.log("Inside callback, this is", this); // 42
console.log(elem);
},
42);
Using thisArg is not that common. Frequently, it is used if an object method is being passed as the callback:
obj = {
vals: [1, 2, 3],
message: "the value is",
alert(x) { alert(this.message + x); },
alertVals() { this.vals.forEach(this.alert, this); }
};
obj.alertVals();
This is an alternative approach to either of
alertVals() { vals.forEach(this.alert.bind(this)); }
alertVals() { vals.forEach(elt => this.alert(elt)); }
thisto be inside the callback? You're confusing thethisof the call toforEachwith thethisArgused for the callback.