怎样判断某个对象是否为另一个对象的原型对象

1. 使用Object.prototype.constructor.prototype进行比较

var obj1 = {name: "李雷"};
var obj2 = {age: 23};
obj1.constructor.prototype === Object.prototype; // true

 

2. 使用: Object.prototype.isPrototypeOf()进行比较

var obj1 = {name: "Lilei"};
var obj2 = Object.create(obj1);

obj1.isPrototypeOf(obj2); // true

 

注意, 这个方法和 instanceof 有点类似, 他的判断逻辑也是往参数对象原型链去找的, 因此就有了下面这些判断为true的情况, 但最后一个因为是一个没有任何属性方法的空对象, 它连prototype都没有, 故返回false

Object.prototype.isPrototypeOf({}) // true
Object.prototype.isPrototypeOf([]) // true
Object.prototype.isPrototypeOf(/xyz/) // true
Object.prototype.isPrototypeOf(Object.create(null)) // false

 

posted on 2019-10-15 13:53  aisowe  阅读(560)  评论(0编辑  收藏  举报

导航