2

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?

1
  • You should really not extend or modify native javascript prototypes (it can create all kinds of unexpected side effects) Commented Jun 5, 2015 at 9:11

3 Answers 3

1

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

2 Comments

But double() is now no longer a method of Number - this has changed the code completely. You can no longer say n.double() to double a number.
@RichieHindle I don't think it changed the code, but I've added the solution for your case too. I actually think if it was used only for this specific case then there was no need to put it inside of the prototype; the first method just adds a static method instead of member one.
0

You need to call your method on an instance of Number:

...
console.log(x.map(function (n) { return n.double(); }));

Comments

0

double is a property of Number prototype, not a global variable.

x.map(function(y){return y.double()});

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.