Javascript: prototype number

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

Why ===does the test return false?

+3
source share
3 answers

Because it thiswill be a Number object, not the initial value of a primitive number, and a comparison of 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 are looking for a fix, add thisto the 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()));
+3
source

, .test(), Number, , - . # Java . (, Java Integer , )

+1

While we test the operator ===, it checks the same type, object.

Here the problem may be due to the creation of different objects.

0
source

Source: https://habr.com/ru/post/1735901/


All Articles