Reputation: 487
I get the following error ReferenceError: double is not defined
Code:
Number.prototype.double = function (){
return this*2;
}
x=[1,2]
console.log(x.map(double));
how can i fix it?
Upvotes: 2
Views: 580
Reputation: 24531
You can't do that like that. The reason is that this
inside of map
is not a number. That's why you cannot do it with a prototype
like you wish.
What you can do is the following: get the passed parameter from map
Number.double = function (e){
return e*2;
}
x=[1,2]
console.log(x.map(Number.double));
EDIT: if you really need the prototype solution, you can do the following:
Number.prototype.double = function (e){
if (e) return e*2;
else return this*2;
}
x=[1,2]
console.log(x.map(Number.prototype.double));
Upvotes: 1
Reputation: 3659
double is a property of Number prototype, not a global variable.
x.map(function(y){return y.double()});
Upvotes: 0
Reputation: 281385
You need to call your method on an instance of Number:
...
console.log(x.map(function (n) { return n.double(); }));
Upvotes: 0