Home > Article > Web Front-end > A brief analysis of the defects of for in in js_javascript skills
The for in statement is used to list the attributes (members) of an object, as follows
Did you notice that obj’s toString, valueOf and other built-in properties (or built-in members, hidden properties and predefined properties) are not output. That is, for in is used to enumerate the displayed members (custom members) of the object.
If you override the built-in properties, then rewrite obj’s toString
What will be output?
1. Under IE6/7/8, it is the same as without rewriting toString. It still only outputs name, getName
2. Under IE9/Firefox/Chrome/Opera/Safari, it outputs name, getName, toString
If you add attributes/methods to the built-in prototype, it will also be traversable during for in
Added method clone to Object.prototype, and all browsers display clone when for in.
This may not be a big deal, because it is generally not recommended to extend the prototype of the built-in constructor, which is also one of the reasons for the decline of Prototype.js. jQuery and Underscore do not extend the self-prototype. The former makes a fuss about the jQuery object, while the latter simply hangs all methods under underscore.
But sometimes in order to be compatible with ES5 or subsequent versions, we will extend the prototype of the built-in constructor on browsers that do not support ES5 (IE6/7/8). In this case, for in will be different in each browser. As follows
IE6/7/8 outputs bind, but other browsers do not. Because bind is natively supported in modern browsers, and for in is not available, IE6/7/8 adds bind to Function.prototype.
To summarize: In cross-browser design, we cannot rely on for in to obtain the member names of objects. We generally use hasOwnProperty to judge.