Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript's "this" pointing to wrong object inside lambda given to array.map

function myClass() { 
    this.nums = [1,2,3]; 
    this.divisor = 2; 
}

myClass.prototype.divideNumsByDivisor = function(){
    return this.nums.map(function(num) {
        return num*this.divisor; 
    });
}

myClass.divideNumsByDivisor() was suposed to multiply each number on it's member variable nums to the value on it's member variable divisor.

This is not working because the function function(num) { return num*this.divisor; } is pointing this to a wrong object.

like image 684
MaiaVictor Avatar asked Jan 17 '23 14:01

MaiaVictor


1 Answers

According to MDN, the 2nd argument to .map(fn, thisArg) is what you want the this ptr to be set to when the callback function is called and it will be set to the global object (e.g window) if you don't pass the 2nd argument.

So, you can make your example work like this:

function myClass() { this.nums = [1,2,3]; this.divisor = 2; }
myClass.prototype.divideNumsByDivisor = function(){
    return this.nums.map(function(num) { return num*this.divisor; }, this);
}
like image 74
jfriend00 Avatar answered Jan 31 '23 07:01

jfriend00