首页 > Web开发 > 详细

JS in和Object.hasOwnProperty()的区别

时间:2021-04-26 10:55:27      阅读:20      评论:0      收藏:0      [点我收藏+]

inObject.hasOwnProperty()都可以用来检测对象中是否具有某个属性,它们最主要的区别在于前者不光检测当前对象,还会检测当前对象原型链中是否具有这个属性,后者只在当前对象自身上检测。

let a = { name: "zhangsan" }
let b = { age: 18 }
Object.setPropertyOf(a, b) // 把b设置为a的原型
console.log("name" in a) // true
console.log("age" in a) // true 因为b中有age属性
console.log(a.hasOwnProperty("name")) // true
console.log(a.hasOwnProperty("age")) // false

基于这个特点,通常我们遍历对象的时候会加上判断防止获取原型链上的属性

function Person() {
  this.name = "zhangsan"
  this.age = 19
  this.hobby = "football"
}

let p1 = new Person()
p1.name = "lisi"
// 不加Object.hasOwnProperty()
for (const key in p1) {
  console.log(key); // name, age, hobby
}
// 加上Object.hasOwnProperty()
for (const key in p1) {
  if (Object.hasOwnProperty(key)) {
    console.log(key); // name
  }
}

JS in和Object.hasOwnProperty()的区别

原文:https://www.cnblogs.com/ychizzz/p/14703277.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!