0

I'm playing with prototype functions and can't understand why the simple example below isn't returning the negative of a number.

Number.prototype.neg = function(x) { return -x };

var num = -1;
var num2 = 1234;

console.log(num.neg());   // returns NaN (and not 1)
console.log(num2.neg());  // returns NaN (and not -1234);

Any idea where I've made the mistake? I know that I could use property getters instead, but I'm working my way through the basics first (and hopefully learning from the mistakes).

1
  • Seriously? Someone voted that down? Commented Feb 6, 2016 at 14:13

1 Answer 1

3

You are not passing any parameter to the function, so according to how you declared the function, you need to do:

num.neg(-1);

Returning -x when x is undefined gives you NaN. But that kind of defeats the purpose. You need to declare the function a bit differently:

Number.prototype.neg = function() { return -this };
Sign up to request clarification or add additional context in comments.

2 Comments

To whoever's hiding behind the downvote, please explain your action.
Thanks Omri. Really obvious once it's pointed it. I'm now referring to -this with no arguments and it works fine.

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.