hasOwnProperty && in

本文深入探讨了JavaScript中检查对象属性存在的两种方法:in运算符和hasOwnProperty方法。in运算符用于检测实例属性和原型链属性,而hasOwnProperty则专注于实例属性。通过具体代码示例,清晰展示了两者的使用场景及区别。

hasOwnProperty && in

in 的用法

用来检查对象中是否存在某个属性(不区分实例属性和原型链属性)

function Person(name) {
  this.name = name
}

Person.prototype.age = 18

Person.prototype.sayHi = function () {
  console.log('hello world');
}

let p1 = new Person()

console.log('name' in p1) // true
console.log('age' in p1) // true
console.log('sayHi' in p1) // true
复制代码

hasOwnProperty

function Animal(dog) {
  this.name = name
}

Animal.prototype.species = '陆地'

Animal.prototype.run = function() {
  console.log('跑的挺快');
}

let a1 = new Animal()

console.log(a1.hasOwnProperty('name')) // true
console.log(a1.hasOwnProperty('species')) // false
console.log(a1.hasOwnProperty('run')) // false
复制代码

总结:

in 运算符: 检查对象中是否存在某个属性(不区分实例属性和原型链属性);
hasOwnProperty 运算符:检查对象中是否存在某个属性(只检查实例属性);

扩展:

  • 判断原型链中是否存在某个属性的方法:
function isProperty(obj, property) {
  return  !obj.hasOwnProperty(property) && (property in obj)
}
复制代码
  • Object.create(null) 创建的对象,hasOwnProperty() 检测不到

  let ownObj = Object.create(null)

  ownObj.name = 'ml'

   console.log(ownObj);

   console.log('name' in ownObj); // true
  //  console.log(ownObj.hasOwnProperty('name')); // false
   console.log(Object.prototype.hasOwnProperty.call(ownObj, 'name')); // true
复制代码

对象没有连接到 Object.prototype 上

转载于:https://juejin.im/post/5c32bb78e51d4551ce6a75a9

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值