Aobj instanceof Bfunction // Bfunction.prototype 是否在 Aobj.__proto__ (A 的原型链)上 ?
Aobj.isPrototypeOf(Bobj) // Aobj 是否在 Bobj.__proto__ (B 的原型链)上?
instanceof 用于判断"左侧的对象"是否是"右侧的构造函数"生成的实例.
相当于:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| function instance(Aobj, Bfunction) { let proto = Aobj.__proto__; while (proto) { if (proto === Bfunction.prototype) { return true; } else { proto = proto.__proto__; } } return false; }
class Parent {} class Child extends Parent {} class Grandson extends Child {}
var c = new Child(); instance(c, Parent); instance({}, Parent); instance(c, Object);
var g = new Grandson(); instance(g, Parent);
|
而 isPrototypeOf 用于判断"左侧的对象"是否在"右侧的对象"的原型链上, 即"右侧的对象"是否会继承"左侧的对象"上的属性和方法.
相当于
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| function isPrototype(Aobj, Bobj) { let proto = Bobj.__proto__; while (proto) { if (proto === Aobj) { return true; } else { proto = proto.__proto__; } } return false; }
class Parent {} class Child extends Parent {} class Grandson extends Child {}
isPrototype(Parent, Grandson);
|
示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class Parent {} class Child extends Parent {} class Grandson extends Child {}
Parent instanceof Child; Child instanceof Parent;
Parent.isPrototypeOf(Child); Child.isPrototypeOf(Parent); Parent.isPrototypeOf(Grandson);
Parent.prototype.isPrototypeOf(Child.prototype); Child.prototype.isPrototypeOf(Parent.prototype);
var c = new Child(); c instanceof Child; c instanceof Parent; c.isPrototypeOf(Child); c.isPrototypeOf(Parent); Child.isPrototypeOf(c); Parent.prototype.isPrototypeOf(c.__proto__);
Child.__proto__ === Parent;
|
参考
Object.prototype.isPrototypeOf() - JavaScript | MDN
instanceof - JavaScript | MDN