標籤:style blog color 使用 io for ar cti
有個很重要的hasOwnProperty()方法,當遍曆對象屬性的時候可以過濾掉從原型鏈上下來的屬性。
// 對象
var man = {
hands: 2,
legs: 2,
heads: 1
};
// 在代碼的某個地方
// 一個方法添加給了所有對象
if (typeof Object.prototype.clone === "undefined") {
Object.prototype.clone = function () {};
}
// 1.
// for-in 迴圈
for (var i in man) {
if (man.hasOwnProperty(i)) { // 過濾
console.log(i, ":", man[i]);
}
}
/* 控制台顯示結果
hands : 2
legs : 2
heads : 1
*/
// 2.
// 反面例子:
// for-in loop without checking hasOwnProperty()
for (var i in man) {
console.log(i, ":", man[i]);
}
/*
控制台顯示結果
hands : 2
legs : 2
heads : 1
clone: function()
*/
另外一種使用hasOwnProperty()的形式是取消Object.prototype上的方法。像是:
for (var i in man) {
if (Object.prototype.hasOwnProperty.call(man, i)) { // 過濾
console.log(i, ":", man[i]);
}
}
其好處在於:在man對象重新定義hasOwnProperty情況下,避免命名衝突;也避免了長屬性尋找對象的所有方法,你可以使用局部變數“緩衝”它。
var i, hasOwn = Object.prototype.hasOwnProperty;
for (i in man) {
if (hasOwn.call(man, i)) { // 過濾
console.log(i, ":", man[i]);
}
}
嚴格來說,不使用hasOwnProperty()並不是一個錯誤。根據任務以及你對代碼的自信程度,你可以跳過它以提高些許的迴圈速度。但是當你對當前對象內容(和其原型鏈)不確定的時候,添加hasOwnProperty()更加保險些。