Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: prototype of Number

var x= 1;  
Number.prototype.test = function () { return this };  
x.test() === x.test() // false  

Why does the === test return false?

like image 316
Eugene Yarmash Avatar asked Jan 20 '26 18:01

Eugene Yarmash


1 Answers

Because this will be a Number object, not the original primitive number value, and comparing two equally created objects will always return false:

{"test":"Hello"} === {"test":"Hello"} // false

// Check the typeof your vars
var x= 1;  
Number.prototype.test = function () { return this };  
x.test() === x.test() // false 
alert("x is a "+typeof(x)+", x.test() is an "+typeof(x.test()));

If you're looking for a fix, cast this to a number

var x= 1;  
Number.prototype.test = function () { return +this };  
x.test() === x.test() // TRUE!
alert("x is a "+typeof(x)+", x.test() is also a "+typeof(x.test()));
like image 147
Andy E Avatar answered Jan 23 '26 08:01

Andy E