JavaScript Patterns 2.4 For-in loop
2014-05-19 11:06 小郝(Kaibo Hao) 阅读(333) 评论(2) 编辑 收藏 举报Principle
- Enumeration should be used to iterate over nonarray objects.
- It's important to use the method hasOwnProperty()when iterating over object properties to filter out properties that come down the prototype chain.
// the object var man = { hands: 2, legs: 2, heads: 1 }; // somewhere else in the code // a method was added to all objects if (typeof Object.prototype.clone = = = "undefined") { Object.prototype.clone = function () {}; } // 1. for-in loop for (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]); } }
作者:小郝
出处:http://www.cnblogs.com/haokaibo/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
出处:http://www.cnblogs.com/haokaibo/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。