简体   繁体   中英

isPrototypeOf() function on primitive

Mozilla.org states that

The isPrototypeOf() method checks if an object exists in another object's prototype chain.

When I create a primitive variable, say

var a = 0;

And check for its [[Prototype]] (not a.prototype ),

console.log(a.__proto__); //on chrome

It prints Number {0, isDivisibleBy2: ƒ, constructor: ƒ, toExponential: ƒ, toFixed: ƒ, …} . Apparently, this value seems to be what's inside the Number.prototype .

So, I expect Number.prototype.isPrototypeOf(a); to return true, since Number.prototype does indeed exist within the prototype chain of a (the __proto __ chain).

But instead, theboutput for Number.prototype.isPrototypeOf(a); is false.

 var a = 0; console.log(a.__proto__); console.log(Number.prototype); console.log(Number.prototype === a.__proto__); console.log(Number.prototype.isPrototypeOf(a));

I think I might be misunderstanding something... I believe that value.__proto__ is the right way to access the prototype chain (understang from this mozilla link ). Is it just that isPrototypeOf() does not work on primitive?

Can someone help me clear up and understand this weird phenomenon?

JavaScript is actually creating a new Number object from the primitive when you access a property on it or call a method, after which the new object is promptly thrown away. That is why you can access the __proto__ property. The primitive, however, is not a Number object.

As you can see in the spec here , the first rule of isProtoTypeOf is "If Type(V) is not Object, return false" (Where V is the value passed to the method).

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