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

routing - AngularJS State management ->load multiple states in one page -

python - GRASS parser() error -

json - Gson().fromJson(jsonResult, Myobject.class) return values in 0's -