Javascript learning notes for objects (4) : for in loop

  • 2020-03-30 03:26:28
  • OfStack

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
}

There are two things to note here. One is that the for in loop ignores the property enumerable is set to false. For example, the length property of an array. Second, because for in traverses the entire prototype chain, performance is affected when the prototype chain is too long.

Use hasOwnProperty filtering

Still use the previous 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 write it, and since we used the hasOwnProperty method, we only output moo this time. If the hasOwnProperty method is not applied, then an error occurs when Object. Prototype extends.
Many frameworks now choose to extend methods from object.prototype, so when we use these frameworks, we will encounter problems if we use a for in loop without hasOwnProperty filtering.

conclusion

It is recommended that you get into the habit of filtering hasOwnProperty properties without making any assumptions about the runtime environment, whether or not the native prototype object is extended.


Related articles: