判断一个属性是定义在对象自己而不是继承自原型链,咱们须要使用从 Object.prototype
继承而来的 hasOwnProperty
方法。hasOwnProperty
方法是 Javascript
中惟一一个处理对象属性而不会往上遍历原型链的。git
// Poisoning Object.prototype Object.prototype.bar = 1; var foo = {goo: undefined}; foo.bar; // 1 'bar' in foo; // true foo.hasOwnProperty('bar'); // false foo.hasOwnProperty('goo'); // true
在这里,只有 hasOwnProperty
能给出正确答案,这在遍历一个对象的属性时是很是必要的。Javascript
中没有其余方法能判断一个属性是定义在对象自己仍是继承自原型链。github
Javascript
并未将 hasOwnProperty
设为敏感词,这意味着你能够拥有一个命名为 hasOwnProperty
的属性。这个时候你没法再使用自己的 hasOwnProperty
方法来判断属性,因此你须要使用外部的 hasOwnProperty
方法来进行判断。ide
var foo = { hasOwnProperty: function() { return false; }, bar: 'Here be dragons' }; foo.hasOwnProperty('bar'); // always returns false // Use another Object's hasOwnProperty and call it with 'this' set to foo ({}).hasOwnProperty.call(foo, 'bar'); // true // It's also possible to use hasOwnProperty from the Object // prototype for this purpose Object.prototype.hasOwnProperty.call(foo, 'bar'); // true
当判断对象属性存在时,hasOwnProperty
是惟一能够依赖的方法。这里还要提醒下,当咱们使用 for in loop
来遍历对象时,使用 hasOwnProperty
将会很好地避免来自原型对象扩展所带来的困扰。oop
http://bonsaiden.github.io/JavaScript-Garden/#object.hasownpropertythis