简体   繁体   English

isPrototypeOf() function 在原语上

[英]isPrototypeOf() function on primitive

Mozilla.org states that Mozilla.org指出

The isPrototypeOf() method checks if an object exists in another object's prototype chain. isPrototypeOf() 方法检查 object 是否存在于另一个对象的原型链中。

When I create a primitive variable, say当我创建一个原始变量时,说

var a = 0;

And check for its [[Prototype]] (not a.prototype ),并检查它的 [[Prototype]] (不是a.prototype ),

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

It prints Number {0, isDivisibleBy2: ƒ, constructor: ƒ, toExponential: ƒ, toFixed: ƒ, …} .它打印Number {0, isDivisibleBy2: ƒ, constructor: ƒ, toExponential: ƒ, toFixed: ƒ, …} Apparently, this value seems to be what's inside the Number.prototype .显然,这个值似乎是Number.prototype里面的值。

So, I expect Number.prototype.isPrototypeOf(a);所以,我希望Number.prototype.isPrototypeOf(a); to return true, since Number.prototype does indeed exist within the prototype chain of a (the __proto __ chain).返回 true,因为Number.prototype确实存在于(__proto __ 链) a原型链中。

But instead, theboutput for Number.prototype.isPrototypeOf(a);但取而代之的是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 ).我想我可能误解了一些东西......我相信value.__proto__是访问原型链的正确方法(从这个 mozilla 链接了解)。 Is it just that isPrototypeOf() does not work on primitive?仅仅是isPrototypeOf()不适用于原语吗?

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.当您访问其上的属性或调用方法时,JavaScript 实际上是从原语中创建一个新的 Number object,然后立即丢弃新的 object。 That is why you can access the __proto__ property.这就是您可以访问__proto__属性的原因。 The primitive, however, is not a Number object.然而,原语不是数字 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).正如您在此处的规范中看到的那样, isProtoTypeOf的第一条规则是“如果 Type(V) 不是 Object,则返回 false”(其中 V 是传递给方法的值)。

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

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