Eugene Yarmash
Eugene Yarmash

Reputation: 149971

Javascript: prototype of Number

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

Why does the === test return false?

Upvotes: 3

Views: 402

Answers (3)

Pavunkumar
Pavunkumar

Reputation: 5345

While we are checking the === operator , it will check same type , object .

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

Upvotes: 0

Andy E
Andy E

Reputation: 344675

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()));

Upvotes: 3

vava
vava

Reputation: 25381

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)

Upvotes: 1

Related Questions