Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why, in JavaScript, does '3 instanceof Number' == false, but '3..method()' will call Number.prototype.method?

Given that a literal number not strictly an instance of Number, why can I call prototype methods of Number (or String, or Boolean) objects on the corresponding literal objects? Is this standard behavior across browsers?

What exactly is happening when this occurs? I suspect it's coercing the literal into the corresponding type before calling the method, because when I inspect typeof this in the method, it's returning 'object' rather than 'number'.

like image 950
Triynko Avatar asked Nov 08 '16 15:11

Triynko


People also ask

How does Instanceof work in JavaScript?

The instanceof operator tests to see if the prototype property of a constructor appears anywhere in the prototype chain of an object. The return value is a boolean value. Its behavior can be customized with Symbol. hasInstance .

What is difference between Typeof and Instanceof?

typeof: Per the MDN docmentation, typeof is a unary operator that returns a string indicating the type of the unevaluated operand. instanceof: is a binary operator, accepting an object and a constructor. It returns a boolean indicating whether or not the object has the given constructor in its prototype chain.

What is instance of number in JS?

The instanceof operator in JavaScript is used to check the type of an object at run time. It returns a boolean value if true then it indicates that the object is an instance of a particular class and if false then it is not.


1 Answers

The literal is not coerced into an instance.

What happens internally, is that an instance is created, the value is copied to the instance and the method is carried out using the instance. Then the instance is destroyed. The literal is not actually being used to carry out the method. This "wrapper" object concept is also used with string primitives when they are used like String objects. This behavior is standard.

3 is a number literal. Not an instance of the Number type. JavaScript has a primitive number type and a native Number object.

From MDN: In contexts where a method is to be invoked on a primitive string or a property lookup occurs, JavaScript will automatically wrap the string primitive and call the method or perform the property lookup.

like image 193
Scott Marcus Avatar answered Oct 03 '22 22:10

Scott Marcus