hasOwnProperty基本概念:
hasOwnProperty() 方法会返回一个布尔值,指示对象自身属性中(非继承属性)是否具有指定的属性,
如果 object 具有带指定名称的属性,则 hasOwnProperty 方法返回 true,否则返回 false。此方法不会检查对象原型链中的属性;该属性必须是对象本身的一个成员。
用法:
obj.hasOwnProperty(prop)
不可以通过obj.hasOwnProperty(prop)判断继承属性
function foo (){
this.sayhi=function(){
console.log('自身属性')
}
this.name='foo'
}
foo.prototype.saygoodbye='saygoodbye';
let myPro=new foo()
console.log(myPro.name) // foo
console.log(myPro.hasOwnProperty('name')) // true
console.log(myPro.hasOwnProperty('toString')) // false
console.log(myPro.hasOwnProperty('hasOwnProperty')) // fasle
console.log(myPro.hasOwnProperty('sayHi')) // true
console.log(myPro.hasOwnProperty('sayGoodBy')) // false
console.log('sayGoodBy' in myPro) // true
遍历一个对象的所有自身属性(忽略其继承属性)
let obj={
name:'foo'
}
for(let key in obj){
if(obj.hasOwnProperty(key)){
console.log('自身属性')
}else{
console.log('继承属性')
}
}
注意 hasOwnProperty 作为属性名
let obj={
hasOwnProperty:function(){
return false
}
name:'foo'
}
console.log(obj.hasOwnProperty('name')) //false
// 如果担心这种情况,可以直接使用原型链上真正的 hasOwnProperty 方法
// 使用另一个对象的`hasOwnProperty` 并且call
({}).hasOwnProperty.call(obj,'name') //true
// 也可以使用 Object 原型上的 hasOwnProperty 属性
Object.prototype.hasOwnProperty.call(obj,'name') //true