I have a simple example below which creates an Object constructor. There is an add
method which attempts to iterate through the arguments
collection by calling the Array.prototype.forEach
method.
The technique works, but I’m having a problem with the this
value.
I have resorted to the trick of assigning this
to a real variable (This
), an using the the real value in the inner function. This works, but I though it should be simpler.
According to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call, I should be able to call this with an optional thisArg
at the beginning. I have tried this in the add2
method. This doesn’t work.
What is the correct way of including a new value for this
argument in the call
method?
function Collection() {
this.data=[];
}
Collection.prototype={
constructor: Collection,
add() {
var This=this;
Array.prototype.forEach.call(arguments,function(value) {
This.data.push(value);
});
},
add2() {
Array.prototype.forEach.call(this,arguments,function(value) {
this.data.push(value);
});
},
}
var c=new Collection();
c.add('apple','banana');
alert(c.data)