PRinciple
// the objectvar man = { hands: 2, legs: 2, heads: 1};// somewhere else in the code// a method was added to all objectsif (typeof Object.prototype.clone = = = "undefined") { Object.prototype.clone = function () {};}// 1. for-in loopfor (var i in man) { if (man.hasOwnProperty(i)) { // filter console.log(i, ":", man[i]); }}/* result in the console hands : 2 legs : 2 heads : 1*/// 2. antipattern:// for-in loop without checking hasOwnProperty()for (var i in man) { console.log(i, ":", man[i]);}/* result in the console hands : 2 legs : 2 heads : 1 clone: function()*/
Call method off of the Object.prototype to avoid naming collisions that man object redefined hasOwnProperty. And use a local variable to cache it.
var i, hasOwn = Object.prototype.hasOwnProperty; for (i in man) { if (hasOwn.call(man, i)) { // filter console.log(i, ":", man[i]); }}
新闻热点
疑难解答