【JS基础】hasOwnProperty 和 isPrototypeOf

发布时间 2023-06-23 21:27:03作者: zjy4fun

hasOwnProperty 检查对象是否含有某个属性,无法检查其原型链上是否含有该属性

isPrototypeOf 检查一个对象是否存在于另一个对象的原型链上,比如parent.isPrototypeof(child)检查 parent 对象是否在 child 对象的原型链上

 

console.log('--------------------  hasOwnProperty  -------------------');
// hasOwnProperty: check if the property is in the object
let obj = {
    name: 'obj',
    age: 18
}
console.log(obj.hasOwnProperty('name'));//true
console.log(obj.hasOwnProperty('toString'));//false


console.log('--------------------  isPrototypeOf  -------------------');
// isPrototypeOf: check if the object is in the prototype chain

// Creating a parent object
const parent = {
    name: 'Parent Object'
};

// Creating a child object that inherits from the parent object
const child = Object.create(parent);
child.age = 10;

// Checking if parent is in the prototype chain of child
console.log(parent.isPrototypeOf(child)); // Output: true

// Creating another object
const otherObj = {
    color: 'red'
};

// Checking if parent is in the prototype chain of otherObj
console.log(parent.isPrototypeOf(otherObj)); // Output: false