简体   繁体   中英

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 .

Considering a trivial class and its implementation like the following:

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

Where .prototype should be inherited from 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.

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 . It's just some tricky semantics.

The fix as I showed above is to called Object.prototype.isPrototypeOf on the C1.prototype itself.

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)`); })(); 

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