views:

69

answers:

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

Why does the === test return false?

+1  A: 

Every time you call .test() a new instance of Number is created, it is much expected behavior, every boxing solution works this way. You can try the same thing in C# and Java and will get absolutely the same result. (Well, Java have pool of Integer objects for small numbers, so you won't get absolutely the same results)

vava
+3  A: 

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()));
Andy E
@eugene: good spot on the syntax errors (the missed closing parenthesis in each code block). Thanks for the edit :)
Andy E
Comparing objects always returns false? Now that's ugly... How to check if two objects are the same one then?
Bart van Heukelom
@Bart: good spot, I meant comparing to equally created objects will return false.
Andy E
A: 
While we are checking the === operator , it will check same type , object . 

Here , the problem may be because of different object creation . 
pavun_cool