【发布时间】:2019-11-06 10:44:38
【问题描述】:
我体验过使用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