1. 示例
  2. 参考

instanceof 与 Object.isPrototypeOf 的区别

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); // true
instance({}, Parent); // false
instance(c, Object); // true

var g = new Grandson();
instance(g, Parent); // true

而 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); // true

示例

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; // false
Child instanceof Parent; // false

Parent.isPrototypeOf(Child); // true
Child.isPrototypeOf(Parent); // false
Parent.isPrototypeOf(Grandson); // true

Parent.prototype.isPrototypeOf(Child.prototype); // true
Child.prototype.isPrototypeOf(Parent.prototype); // false

var c = new Child();
c instanceof Child; // true
c instanceof Parent; // true
c.isPrototypeOf(Child); // false
c.isPrototypeOf(Parent); // false
Child.isPrototypeOf(c); // false
Parent.prototype.isPrototypeOf(c.__proto__); // true

Child.__proto__ === Parent; // true

参考

Object.prototype.isPrototypeOf() - JavaScript | MDN
instanceof - JavaScript | MDN