看代码输出
let person = {
age:10,
name:'lily'
};
// 方式 1 in operator 查找对象和其原型链上是否存在某个属性
console.log('name' in person); // true
console.log('toString' in person); // true
console.log('count' in person); // false
// 方式 2 Reflect.has() 查找对象和其原型链上是否存在某个属性
console.log(Reflect.has(person,'name')); // true
console.log(Reflect.has(person,'toString')); // true
console.log(Reflect.has(person,'count')); // false
// 方式 3 obj.hasOwnProperty 查找对象是否存在某个属性(不会向上查找原型链上的)
console.log(person.hasOwnProperty('name')); // true
console.log( person.hasOwnProperty('count')); //
console.log( person.hasOwnProperty('toString')); // false
// 方式 4 Object.hasOwn()
console.log(Object.hasOwn(person,'name')); // true
console.log(Object.hasOwn(person,'toString')); // false
console.log(Object.hasOwn(person,'count')); // false
// 方式 5 Object.prototype.hasOwnProperty() ,同obj.hasOwnProperty,obj也是从原型链上继承来的
总结
in operator 和Reflect.has()会查找对象和其原型链上, hasOwnProperty和hasOwn 只找对象上的(own:自己的、本人的)