Javascript "this" points to the wrong object inside the lambda given to the .map array

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 suggested to multiply each number by its member variable nums by the value on it of the member variable divisor .

This does not work because the function function(num) { return num*this.divisor; } function(num) { return num*this.divisor; } indicates an invalid object.

+4
source share
2 answers

According to MDN , the 2nd argument .map(fn, thisArg) is what you want to set for the this ptr parameter when the callback function is called, and it will be set for the global object (e.g. window ) if you don't pass the second 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); } 
+7
source

You need to define a link to your instance in the scope, and then get it later in another instance. Update your method to this

 myClass.prototype.divideNumsByDivisor = function(){ var me = this; return this.nums.map(function(num) { return num*me.divisor; }); } 
+2
source

Source: https://habr.com/ru/post/1394331/


All Articles