JavaScript|原型判断

对象是否有属于自己的属性

通过hasOwnProperty()方法判断对象是否有属于自己的属性,而不是原型的属性。

var obj = {
    name: 'obj',
};

var obj1 = Object.create(obj, {
    age: {
        value: 18,
        enumerable: true,
        configurable: true,
        writable: true,
    },
});

console.log(obj1); // { age: 18 }
console.log(obj1.hasOwnProperty('age')); // true
console.log(obj1.hasOwnProperty('name')); // false

判断属性在对象或者原型链上

通过in/for in可以判断属性在对象或者原型链上。

console.log('age' in obj1); // true
for (var i in obj1) {
    console.log(i); // age name
}

检测构造函数的pototype,是否出现在某个实例对象的原型链上

通过instanceof判断构造函数的prototype是否出现在某个实例对象的原型链上,但不能用于实例对象。

function inheritPrototype(SubType, SuperType) {
  SubType.prototype = Object.create(SuperType.prototype)
  Object.defineProperty(SubType.prototype, "constructor", {
    enumerable: false,
    configurable: true,
    writable: true,
    value: SubType
  })
}


function Person() {

}

function Student() {

}

inheritPrototype(Student, Person)

var stu = new Student()

console.log(stu instanceof Student) // true
console.log(stu instanceof Person) // true
console.log(stu instanceof Object) // true

检测某个对象,是否出现在某个实例对象的原型链上

通过isPrototypeOf判断某个对象,是否出现在某个实例对象的原型链上。

function Person() {

}

var p = new Person()

console.log(p instanceof Person) // true
console.log(Person.prototype.isPrototypeOf(p)) // true

// 
var obj = {
  name: "why",
  age: 18
}

var info = Object.create(obj)

console.log(info instanceof obj) // trows a TypeError
console.log(obj.isPrototypeOf(info)) // true