You can store this in variable:
var self = this;
this.addNewObjects = function(arr){
arr.forEach(function(obj) {
self.addObject(new Obj(obj.prop1, obj.prop2));
});
}
or use bind:
this.addNewObjects = function(arr) {
arr.forEach(function(obj) {
this.addObject(new Obj(obj.prop1, obj.prop2));
}.bind(this));
}
And side note, without those this
will be window object not obj. This
is always object that was created using new keyword or window object if it's normal function. In strict mode this
will be undefined in this case.
UPDATE: and with ES6 you can use arrow function:
this.addNewObjects = function(arr) {
arr.forEach((obj) => {
this.addObject(new Obj(obj.prop1, obj.prop2));
});
}
arrow functions don't have their own this
and they get it from outer scope.
UPDATE2: from @viery365 comment you can use this as second argument to forEach and it will make context for the function:
this.addNewObjects = function(arr) {
arr.forEach(function(obj) {
this.addObject(new Obj(obj.prop1, obj.prop2));
}, this);
}
You can read this on MDN forEach page
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…