Jackson Xie Jackson Xie - 4 months ago 52
Javascript Question

this context in forEach

I was reading the Mozilla Documentation, but I don't understand the

which is passed into the function. Could anyone explain more about the usage of the
argument here?

function Counter() {
this.sum = 0;
this.count = 0;

Counter.prototype.add = function(array) {
array.forEach(function(entry) {
this.sum += entry;
}, this); //Why is this passed here?

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


Per the Mozilla documentation:

thisArg Optional

Value to use as this when executing callback.

And also:

If a thisArg parameter is provided to forEach(), it will be passed to callback when invoked, for use as its this value. Otherwise, the value undefined will be passed for use as its this value. (Emphasis added)

What passing the thisArg to forEach does is bind the context. By default, this in forEach is the global window object, because undefined is used for this. Passing the context permits you to access things from that context.

In the prototype, this is the Counter constructor, and passing then allows you to set the context of which this is inside the forEach. So, instead of this being window inside the forEach, it is now Counter, and you can access variables such as this.sum otherwise not available due to the context.