var x= 1;
Number.prototype.test = function () { return this };
x.test() === x.test() // false
Why does the ===
test return false?
var x= 1;
Number.prototype.test = function () { return this };
x.test() === x.test() // false
Why does the ===
test return false?
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)
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()));
While we are checking the === operator , it will check same type , object .
Here , the problem may be because of different object creation .