3

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;
2
  • Why not a for loop? Commented Apr 4, 2015 at 17:19
  • @Vld, Just working around map because it looks clean. Looks like should use for loop. Commented Apr 4, 2015 at 17:21

2 Answers 2

2

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;
    }
};
Sign up to request clarification or add additional context in comments.

2 Comments

Excellent. One more thing. It is not necessary but can is there a way to get Index of the item inside map?
Yes, map has three built in arguments, they are map(currentValue, index, array)
1

Array.prototype.map method accepts optional argument: object value to be used as this. So your code will become as simple as:

add: function () {
    this.toAdd.map(function (num) {
        this.sum += num;      
    }, this);
    return this.sum;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.