简体   繁体   English

Constructor.prototype不在原型链中?

[英]Constructor.prototype not in the prototype chain?

related: Confusion about protype chain , primitives and objects 相关: 关于原型链,基元和对象的混淆

in Firebug console : 在Firebug控制台中:

a = 12
a.constructor.prototype.isPrototypeOf(a) // prints 'false'

I think this should print true 我认为这应该是true

a = 12 creates a primitive number, which is not quite the same as a Number object. a = 12创建一个原始数字,它与Number对象不完全相同。 Primitives are implicitly cast to objects for purposes of property access. 为了属性访问的目的,基元被隐式地转换为对象。

a = 12; //a is a primitive
b = new Number(12); //b is an object
a.constructor.prototype.isPrototypeOf(a); //false because a is primitive
b.constructor.prototype.isPrototypeOf(b); //true because b is an object

As per the ECMAScript spec : 根据ECMAScript规范

When the isPrototypeOf method is called with argument V , the following steps are taken: 使用参数V调用isPrototypeOf方法时,将执行以下步骤:

  1. If V is not an object, return false . 如果V不是对象,则返回false

primitive numbers are not, strictly speaking, objects. 严格来说,原始数字不是对象。

a = new Number(12);
a.constructor.prototype.isPrototypeOf(a) // prints 'true'

I'm not smart enough to tell you why I just know that this is how it is. 我不够聪明,告诉你为什么我只知道它是这样的。 And yes, it's weird. 是的,这很奇怪。

Now, you could say " 12 is a primitive and new Number(12) is an object". 现在,你可以说12是一个原始的, new Number(12)是一个对象”。 But how do you explain this? 但你怎么解释这个?

(12).toFixed(3); // "12.000"

Apparently somewhere JavaScript is deciding the primitive might as well be an object. 显然,某些地方JavaScript正在决定原始可能也是一个对象。

Why does this distinction exist? 为什么存在这种区别? How do you convert between the two forms? 你如何在两种形式之间转换? How does this impact performance? 这对性能有何影响? All questions related to this question that I don't have the answer to. 所有与此问题相关的问题我都没有答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM