hasOwnProperty与in都是被用于检查对象属性。但他们的检查范围不通。
hasOwnProperty方法仅检查自身属性,而不考虑原型链上的属性。如果检查的属性是来自原型链的,那么返回false。
in运算符则检查自身以及它的原型链上是否存在该属性。如果属性存在自身或原型链,in都会返回true。
function parent() {
this.parentData = 1
}
function children() {
this.childrenData = 1
}
children.prototype = new parent()
const child = new children();
console.log('childrenData' in child) // true
console.log('parentData' in child) // true
console.log(child.hasOwnProperty('childrenData')) // true
console.log(child.hasOwnProperty('parentData')) // false