首頁  >  文章  >  web前端  >  Javascript學習筆記之 物件篇(三) : hasOwnProperty_基礎知識

Javascript學習筆記之 物件篇(三) : hasOwnProperty_基礎知識

WBOY
WBOY原創
2016-05-16 16:43:221096瀏覽
// 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 將會很好地避免來自原型物件擴充所帶來的困擾。

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn