instanceof和isPrototypeOf的区别

180 阅读1分钟
  • instanceof
    • 官方定义:用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。
    • 用于判断一个对象是否是某个构造函数的(子代构造函数的)实例
function Person() {}

const person = new Person();
console.log(person instanceof Person); // true
console.log(person instanceof Object); // true
  • isPrototypeOf
    • 官方定义:用于检查一个对象是否存在于另一个对象的原型链中。
function Person() {}
function Test() {}

const test = new Test();
Person.prototype = test;
const person = new Person();

console.log(test.isPrototypeOf(person)); // true
console.log(Test.prototype.isPrototypeOf(person)); // true

image.png

由上图可以明显看出,test和Test.prototype在person的原型链上,故上面两个打印都是true