Javascript prototype function failure -


i'm playing prototype functions , can't understand why simple example below isn't returning negative of 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 i've made mistake? know use property getters instead, i'm working way through basics first (and learning mistakes).

you not passing parameter function, according how declared function, need do:

num.neg(-1); 

returning -x when x undefined gives nan. kind of defeats purpose. need declare function bit differently:

number.prototype.neg = function() { return -this }; 

Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -