Reputation: 149971
var x= 1;
Number.prototype.test = function () { return this };
x.test() === x.test() // false
Why does the ===
test return false?
Upvotes: 3
Views: 402
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
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
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