Object of Javascript learning notes (4): for in Loop

Source: Internet
Author: User
Tags hasownproperty

Example 1:

// Poisoning Object.prototypeObject.prototype.bar = 1;var foo = {moo: 2};for(var i in foo) { console.log(i); // prints both bar and moo}

Here we should pay attention to two points. First, the for in loop will ignore the attribute set to false by enumerable. For example, the length attribute of an array. Second, because for in will traverse the entire prototype chain, when the prototype chain is too long, it will affect the performance.

Enumerable is a strange word. In fact, it is difficult for you to find its shadow in javascript, and it is actually borrowed from ruby by the author. The purpose of creating an enumerable is not to be used independently, but to use a "mixed" method. Many Prototype methods use enumerable, which is the cornerstone of prototype. I will not describe it in detail here. For details, refer to-Enumerable.
Because we cannot change the behavior of the for in loop, we can only use other methods to filter out the attributes that do not want to appear in the loop): hasOwnProperty we know that the hasOwnProperty method can do this.

Use hasOwnProperty Filter

The previous example is still used:

// Poisoning Object.prototypeObject.prototype.bar = 1;var foo = {moo: 2}; for(var i in foo) { if (foo.hasOwnProperty(i)) {  console.log(i); } }

This is the only correct method. Because we have used the hasOwnProperty method, only moo is output this time. If the hasOwnProperty method is not applicable, an error occurs when Object. prototype is extended.
Many frameworks now use the extension method from Object. prototype. Therefore, if we use these frameworks, we will encounter problems when using a for in loop that does not use hasOwnProperty filtering.

Summary

We recommend that you develop a good habit of filtering attributes by hasOwnProperty. Do not make any assumptions about the runtime environment, regardless of whether the native prototype object is extended or not.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.