![](/img/trans.png)
[英]Why o.prototype.isPrototypeof is not a function, my javascript throws an exception
[英]isPrototypeOf() function on primitive
isPrototypeOf() 方法檢查 object 是否存在於另一個對象的原型鏈中。
當我創建一個原始變量時,說
var a = 0;
並檢查它的 [[Prototype]] (不是a.prototype
),
console.log(a.__proto__); //on chrome
它打印Number {0, isDivisibleBy2: ƒ, constructor: ƒ, toExponential: ƒ, toFixed: ƒ, …}
。 顯然,這個值似乎是Number.prototype
里面的值。
所以,我希望Number.prototype.isPrototypeOf(a);
返回 true,因為Number.prototype
確實存在於(__proto __ 鏈) a
原型鏈中。
但取而代之的是Number.prototype.isPrototypeOf(a);
是假的。
var a = 0; console.log(a.__proto__); console.log(Number.prototype); console.log(Number.prototype === a.__proto__); console.log(Number.prototype.isPrototypeOf(a));
我想我可能誤解了一些東西......我相信value.__proto__
是訪問原型鏈的正確方法(從這個 mozilla 鏈接了解)。 僅僅是isPrototypeOf()
不適用於原語嗎?
有人可以幫我清理並理解這種奇怪的現象嗎?
當您訪問其上的屬性或調用方法時,JavaScript 實際上是從原語中創建一個新的 Number object,然后立即丟棄新的 object。 這就是您可以訪問__proto__
屬性的原因。 然而,原語不是數字 object。
正如您在此處的規范中看到的那樣, isProtoTypeOf
的第一條規則是“如果 Type(V) 不是 Object,則返回 false”(其中 V 是傳遞給方法的值)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.