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
标签:console,log,parent,isPrototypeOf,JS,hasOwnProperty,child From: https://www.cnblogs.com/zjy4fun/p/17500217.html