关于hasOwnProperty的基本概念

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值