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

风格不统一 提交于 2020-01-10 04:47:05

问题


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'.


回答1:


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.



来源:https://stackoverflow.com/questions/40491240/why-in-javascript-does-3-instanceof-number-false-but-3-method-will

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!