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.
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);
}
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