我并不期待两者之间的区别。Airbnb已经做了很好的工作来解释它,https://github.com/airbnb/javascript#objects--prototype-builtins。
考虑一个平凡的类及其实现,如下所示:
class C1 {}
const c1Imp = new C1();.prototype应该从对象继承的地方。
为什么以下内容不是等价的呢?
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)`);
})();
问题标题不太清楚,请随意编辑。
发布于 2017-02-03 22:42:12
你应该这样做:
Object.prototype.isPrototypeOf.call(C1.prototype, c1Imp) // true在第一个示例中,您在C1本身上调用了C1方法,而在第二个示例中,您在C1.prototype上调用了isProtoTypeOf。,这只是一些棘手的语义。
正如我上面所显示的,修复是在C1.prototype本身上调用C1.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)`);
})();
https://stackoverflow.com/questions/42034136
复制相似问题