判斷一個屬性是定義在對象本身而不是繼承自原型鏈,我們需要使用從 Object.prototype
繼承而來的 hasOwnProperty
方法。hasOwnProperty
方法是 Javascript
中唯一一個處理對象屬性而不會往上遍歷原型鏈的。
// 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
中沒有其他方法能判斷一個屬性是定義在對象本身還是繼承自原型鏈。
hasOwnProperty 作爲屬性
Javascript
並未將 hasOwnProperty
設爲敏感詞,這意味着你可以擁有一個命名爲 hasOwnProperty
的屬性。這個時候你無法再使用本身的 hasOwnProperty
方法來判斷屬性,所以你需要使用外部的 hasOwnProperty
方法來進行判斷。
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
將會很好地避免來自原型對象擴展所帶來的困擾。
轉載於: https://segmentfault.com/a/1190000000480531