簡體   English   中英

Object.prototype.isPrototypeOf與obj.prototype.isPrototypeOf

[英]Object.prototype.isPrototypeOf vs. obj.prototype.isPrototypeOf

我不期待彼此之間的差異。 Airbnb已經在樣式指南存儲庫中對此做出了出色的解釋。

考慮一個瑣碎的類及其實現,如下所示:

class C1 {}
const c1Imp = new C1();

其中.prototype應該從Object繼承。

為什么以下等效項不成立?

console.info(Object.prototype.isPrototypeOf.call(C1, c1Imp)); // false
console.info(C1.prototype.isPrototypeOf(c1Imp)); // true

  (() => { class C1 {} const c1Imp = new C1(); console.info(c1Imp.constructor.name); console.info(`${Object.prototype.isPrototypeOf.call(C1, c1Imp)} (should be true)`); console.info(`${C1.prototype.isPrototypeOf(c1Imp)} (should be true)`); class C2 {} const c2Imp = new C2(); console.info(c2Imp.constructor.name); console.info(`${Object.prototype.isPrototypeOf.call(C1, c2Imp)} (should be false)`); console.info(`${C1.prototype.isPrototypeOf(c2Imp)} (should be false)`); })(); 

PS:問題標題不是很清楚,請隨時進行適當的編輯。

您應該這樣做:

Object.prototype.isPrototypeOf.call(C1.prototype, c1Imp) // true

在第一個示例中,您在C1本身上調用Object.prototype.isPrototypeOf方法,而在第二個示例中,您在isProtoTypeOf上調用C1.prototype 這只是一些棘手的語義。

此修復程序正如我上面顯示是名為Object.prototype.isPrototypeOfC1.prototype本身。

查看更新的代碼段:

  (() => { class C1 {} const c1Imp = new C1(); console.info(c1Imp.constructor.name); console.info(`${Object.prototype.isPrototypeOf.call(C1.prototype, c1Imp)} (should be true)`); console.info(`${C1.prototype.isPrototypeOf(c1Imp)} (should be true)`); class C2 {} const c2Imp = new C2(); console.info(c2Imp.constructor.name); console.info(`${Object.prototype.isPrototypeOf.call(C1, c2Imp)} (should be false)`); console.info(`${C1.prototype.isPrototypeOf(c2Imp)} (should be false)`); })(); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM