thisinside a callback forEachrefers to a global object window. To set the callback context, use the second argument Array#forEachto pass the context.
this.array.forEach(function (value) {
this.sum += value;
}, this);
function ArrayAdder(_array) {
this.sum = 0;
this.array = _array || [];
}
ArrayAdder.prototype.computeTotal = function () {
this.sum = 0;
this.array.forEach(function (value) {
this.sum += value;
}, this);
return this.sum;
};
var myArray = new ArrayAdder([1, 2, 3]);
console.log(myArray.computeTotal());
document.write(myArray.computeTotal());
Run codeHide result
If you are looking for an alternative you can use Array#reduceusing the Arrow Function
var sum = arr.reduce((x, y) => x + y);
var arr = [1, 2, 3];
var sum = arr.reduce((x, y) => x + y);
document.write(sum);
Run codeHide result source
share