首页 > 解决方案 > 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'));

标签: javascript

解决方案


一个主要区别是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。


推荐阅读