In the following add method of myObj how can I get this inside map? In other words, this when wrapped to map, points to that anonymous function inside map. How can I get this there?
Note: Workarounds like creating a new variable
temp_sumand adding and returning are not preferred. Because, I might have to do some tests inside them using the this keyword.
var myObj = {
sum : 0,
toAdd : [2,3,4],
add : function(){
this.toAdd.map(function(num){
this.sum += num //<-- How to get this.sum from here
})
return this.sum;
}
};
var m = Object.create(myObj);
var _sum = m.add();
document.getElementById("test").innerHTML = _sum;
You could use bind
var myObj = {
sum : 0,
toAdd : [2,3,4],
add : function(){
this.toAdd.map(function(num, index){
this.sum += num;
}.bind(this))
return this.sum;
}
};
or reduce
var myObj = {
sum : 0,
toAdd : [2,3,4],
add : function(){
this.sum = this.toAdd.reduce(function(a,b){
return a + b;
});
return this.sum;
}
};
or a for loop
var myObj = {
sum : 0,
toAdd : [2,3,4],
add : function(){
for (var i=0; i<this.toAdd.length; i++) {
this.sum += this.toAdd[i];
}
return this.sum;
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With