javascript - Javascript object.hasOwnProperty() 与 Reflect.has()
问题描述
我体验过object.hasOwnProperty('property')
用于验证 Javascript 对象,最近注意到它Reflect.has()
也用于验证对象属性。但是,两者的功能几乎相同,但我想了解使用的最佳实践Reflect.has()
以及哪一个会带来更好的性能。
我注意到,如果它不是对象,则hasOwnProperty
不会引发任何错误,而是Reflect.has()
会引发错误。
var object1 = {
property1: 42
};
//expected output: true
console.log(object1.hasOwnProperty('property1'));
console.log(Reflect.has(object1, 'property1'));
// expected output: true
console.log(Reflect.has(object1, 'property2'));
// expected output: false
console.log(Reflect.has(object1, 'toString'));
//For Negative case scenario
var object2 ="";
// expected output: false
console.log(object2.hasOwnProperty('property1'))
// error
console.log(Reflect.has(object2, 'property1'));
解决方案
一个主要区别是Reflect.has
它将检查对象的任何内部原型是否具有密钥,而hasOwnProperty
仅检查对象本身是否具有密钥:
const proto = { foo: 'foo' };
const obj = Object.create(proto);
console.log(Reflect.has(obj, 'foo'));
console.log(obj.hasOwnProperty('foo'));
如果要检查对象本身是否具有属性,并且不是继承属性,则绝对应该使用hasOwnProperty
.
另一个重要的区别是Reflect.has
需要 ES6 支持,而hasOwnProperty
自 ES3 以来就存在,所以如果你使用Reflect.has
并需要对旧版浏览器的支持,请确保包含一个 polyfill。
推荐阅读
- javascript - TypeError:res.status 不是函数
- css - 将 YouTube 嵌入页面居中
- html - 当文件位于名为 E: 的磁盘中而 localhost 的文件位于 C: 中时,是否可以使用绝对路径在 html 中显示视频或图像?
- java - 如何在 selenium 中运行高优先级测试
- java - 如何在 fastnate 生成的 SQL 中附加模式名称
- java - 为什么当我输入数字时我的编程不起作用:600851475143
- excel - 基于另一个单元格自动向一个单元格添加值
- xml - 雪花 XML 解析返回 NULL - 字段名称中的空格?
- javascript - 在选择元素上设置回调 onBlur
- java - Thymeleaf - 基于对象属性值的条件渲染