First example:
Poisoning Object.prototype
Object.prototype.bar = 1;
var foo = {Moo:2};
for (var i in foo) {
console.log (i);//Prints both bar and Moo
}
Here we pay attention to two points, one for the in loop ignores the enumerable set to false. For example, the length property of an array. Second, because for-in will traverse the entire prototype chain, it can affect performance when the prototype chain is too long.
Enumerable is a very unfamiliar word, in fact, it is difficult to find its shadow in JavaScript, and it is actually the author from the reference from Ruby. The purpose of creating enumerable is not to use it independently, but to adopt a "mixed" approach, and many methods in Prototype are mixed with enumerable, so it can be said to be the cornerstone of Prototype. Here does not do the detailed introduction, the detailed content may refer to-enumerable.
Since we can't change the behavior of the for-in loop itself, we can only take other steps to filter out the attributes that don't want to appear in the loop, through the JavaScript Learning notes Object (iii): hasOwnProperty we know hasOwnProperty method is possible to do this.
Using hasOwnProperty filtering
Still use the last example:
Poisoning Object.prototype
Object.prototype.bar = 1;
var foo = {Moo:2};
for (var i in foo) {
if (Foo.hasownproperty (i)) {
console.log (i);
}
}
This is the only correct way to do this, because we have a practical hasownproperty method, so this time we only output moo. If the hasOwnProperty method is not applicable, an error occurs when the Object.prototype is extended.
Many frameworks now choose to extend methods from Object.prototype, so when we use these frameworks, we run into problems when we use a for in loop without hasownproperty filtering.
Summarize
It is recommended that you develop a good habit of hasownproperty filtering properties, and do not make any assumptions about the operating environment, or whether the original prototype object is expanded.