简体   繁体   中英

Constructor.prototype not in the prototype chain?

related: Confusion about protype chain , primitives and objects

in Firebug console :

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

I think this should print true

a = 12 creates a primitive number, which is not quite the same as a Number object. 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 :

When the isPrototypeOf method is called with argument V , the following steps are taken:

  1. If V is not an object, return 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". But how do you explain this?

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

Apparently somewhere JavaScript is deciding the primitive might as well be an object.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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