JavaScript中Object对象原型上的hasOwnProperty()用来判断一个属性是定义在对象本身而不是继承自原型链。
1.用户可能有一个使用Object.create(null)创建的JavaScript对象,它将有一个null [[Prototype]]链,因此不会有hasOwnProperty()可用
2.因为javascript没有将hasOwnProperty作为一个敏感词,所以我们很有可能将对象的一个属性命名为hasOwnProperty,这样一来就无法再使用对象原型的 hasOwnProperty 方法来判断属性是否是来自原型链。
var foo = {
hasOwnProperty: function() {
return false;
},
bar: 'Here be dragons'
};
foo.hasOwnProperty('bar'); // 始终返回 false
不能使用该对象.hasOwnProperty 这种方法,怎么来解决这个问题呢?我们需要使用原型链上真正的 hasOwnProperty 方法:
({}).hasOwnProperty.call(foo, 'bar'); // true
// 或者:
Object.prototype.hasOwnProperty.call(foo, 'bar'); // true
总的来说,使用Object.prototype.hasOwnProperty.call()有三方面的原因:
- If obj inherits from null not Object.prototype
- If hasOwnProperty has been redeclared on obj
- If hasOwnProperty has been redeclared in obj's prototype chain
网友评论