简体   繁体   English

Object.prototype.isPrototypeOf与obj.prototype.isPrototypeOf

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

I am not looking forward the differences between one and the other. 我不期待彼此之间的差异。 Airbnb already does a great job explaining about it on the style guides repository . Airbnb已经在样式指南存储库中对此做出了出色的解释。

Considering a trivial class and its implementation like the following: 考虑一个琐碎的类及其实现,如下所示:

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

Where .prototype should be inherited from Object . 其中.prototype应该从Object继承。

Why isn't the following equivalent? 为什么以下等效项不成立?

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: the question title isn't very clear, feel free to edit as appropriate. PS:问题标题不是很清楚,请随时进行适当的编辑。

You should do this instead: 您应该这样做:

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

In your first example, you were calling the Object.prototype.isPrototypeOf method on C1 itself, while in the second example, you were calling isProtoTypeOf on the C1.prototype . 在第一个示例中,您在C1本身上调用Object.prototype.isPrototypeOf方法,而在第二个示例中,您在isProtoTypeOf上调用C1.prototype It's just some tricky semantics. 这只是一些棘手的语义。

The fix as I showed above is to called Object.prototype.isPrototypeOf on the C1.prototype itself. 此修复程序正如我上面显示是名为Object.prototype.isPrototypeOfC1.prototype本身。

Check out the updated snippet: 查看更新的代码段:

  (() => { 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