hasOwnProperty 和 in 的区别

in 运算符和 hasOwnProperty 方法是检查对象是否包含特定键的常用方法。

const person = {
  name: 'foo'
}

console.log('name' in person) // true
console.log(person.hasOwnProperty('name')) // true

区别

对于继承的属性,in 将返回 true。顾名思义,hasOwnProperty 将检查属性是否为自身所有,并忽略继承的属性。

让我们重用上一个示例中的 person 对象。由于它是一个具有内置属性的 JavaScript 对象,例如constructor__proto__,因此以下检查返回 true

'constructor' in person // true
'__proto__' in person // true
'toString' in person // true

hasOwnProperty 在检查这些属性和方法时返回 false

person.hasOwnProperty('constructor') // false
person.hasOwnProperty('__proto__') // false
person.hasOwnProperty('toString') // false

对于类的 getset 方法,hasOwnProperty 也返回 false

例如,我们有一个表示三角形的简单类:

class Triangle {
  get vertices() {
    return 3
  }
}

// 创建新实例
const triangle = new Triangle()

尽管 verticestriangle 的属性:

triangle.vertices // 3
'vertices' in triangle // true

hasOwnProperty 仍然忽略它:

triangle.hasOwnProperty('vertices') // false

建议

要检查属性是否存在,请使用 hasOwnProperty。使用 in 检查方法的存在。

全部评论

相关推荐

企业都这么缺人了吗?缺人为什么还给白菜价!
真起不了响亮的名字:我给你出个主意,把公司报出来,让牛友去投,岂不美哉
点赞 评论 收藏
分享
点赞 评论 收藏
分享
程序员牛肉:这一眼假啊,基本上都是骗人的,不然就涉及到职位贪腐了,就像之前华为的OD事件,看你运气好不好了
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
06-19 17:02
鼠鼠深知pdd的强度很大,但是现在没有大厂offer,只有一些不知名小厂我是拒绝等秋招呢,还是接下?求大家帮忙判断一下!
水中水之下水道的鼠鼠:接了再说,不图转正的话混个实习经历也不错
投递拼多多集团-PDD等公司10个岗位 >
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务