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

 

评论关闭
IT源码网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!

怎样理解Object.create()方法