for-in循环(for-in Loops) --- 使用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()
*/

代码来源:深入理解JavaScript系列(1):编写高质量JavaScript代码的基本要点

你可能感兴趣的:(for-in循环(for-in Loops) --- 使用hasOwnProperty()方法过滤掉从原型链上下来的属性。)