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

前端 未结 1 1463
傲寒
傲寒 2020-12-10 20:28

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 objec

相关标签:
1条回答
  • 2020-12-10 20:31

    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.

    0 讨论(0)
提交回复
热议问题