A brief analysis of the defects of for in js

  • 2020-03-30 00:42:25
  • OfStack

The for in statement is used to list the properties (members) of the object, as follows


var obj = { name:"jack",
      getName:function(){return this.name}
};
//The output name, getName     
for(var atr in obj) {
    alert(atr);
}

Notice that there are no built-in properties (or built-in members, hidden properties, and predefined properties) that output obj such as toString, valueOf, etc. For in is used to enumerate the display members of the object (custom members).

If you override the built-in properties, then you override obj's toString


var obj = {name:"jack",
      getName:function(){return this.name},
      toString:function(){return "I'm jack."}
}
for(var atr in obj) {
    alert(atr);
}

What's going to be output?
1, ie6/7/8 and did not overwrite toString, still only output name,getName
2, ie 9 / Firefox/Chrome/Opera/Safari print name, getName, toString

If you add properties/methods to the built-in stereotype, then for in is also traversable


Object.prototype.clone = function() {}
var obj = {
    name: 'jack',
    age: 33
}
// name, age, clone
for (var n in obj) {
    alert(n)
}

Add the method clone to object.prototype, and all browsers display clone for in.

This is probably not a big deal, because it's generally not recommended to extend prototypes with built-in constructors, which is one of the reasons that prototype.js went down the tubes. JQuery and Underscore do not extend the autoarchetype, with the former acting on jQuery objects and the latter simply hanging all methods on the Underscore.


if (!Function.prototype.bind) {
    Function.prototype.bind = function(scope) {
        var fn = this
        return function () {
            fn.apply(scope, arguments)
        }
    }
}
function greet(name) {  
    alert(this.greet + ', ' + name)
}
for (var n in greet) {
    alert(n)
}

In summary: in cross-browser design, we can't rely on for in to get the member name of the object, we usually use hasOwnProperty to judge.


Related articles: