JavaScript-Read the study notes of Uncle Tom's Blog

Source: Internet
Author: User
Tags hasownproperty


Part1---------------------------------------------------------------------------------------------------------

1. Preface

These two days looked at Uncle Tom's "in-depth understanding JS series" In the basic part, according to their actual situation, did a reading notes, recorded part of the problem is easy to stumbling. Write an article for everyone to share.

2. About Htmlcollection "real-time query"
var divs = document.getElementsByTagName ("div"),      i;  for (i = 0; i < divs.length; i++) {      //...}

Performance issues can occur in the above code. The problem is that DIVs is an object of the htmlcollection type that, when it gets the data, will re-parse the calculation from the DOM. Therefore, in the For loop here, each step of the loop performs a divs.length calculation, which will cause the browser to iterate through the DOM tree again.
Therefore, the length property value of divs should be calculated early outside of the loop. As follows:

var divs = document.getElementsByTagName ("div"),    i,    = divs.length;  for (i = 0; i < length; i++) {    //...}
3. For: In ... , note hasownproperty validation
var obj = {                ten                            };                         // Note the phrase code             - ;             var item;              for inch obj) {                Console.log (item);            }

In the above code, pay attention to the middle label comment sentence. This code is added with no addition, will be on the following for: In.. The loop has an impact. Add the Output "C", do not add the output "C". The reason is simple, for. In.. Loops can not only traverse the properties of the Obj object itself, but also traverse the properties in the obj prototype.

To block out the properties in the prototype, use the hasOwnProperty function, as follows:

            for inch obj) {                if  (Obj.hasownproperty (item)) {                //if ( Object.prototype.hasOwnProperty.call (obj, item)) {                    console.log (item);                }            }

These two if judgment statements, all can be used, the effect is the same. The first code is good readability and the second is relatively efficient. Suggestion, no special case, with the first can.

4. Old problem: closure problem of generating function/event in loop
var events = [],                = 0;         // Looping create function         for (; i <; i++) {            function  () {                console.log (i);            };        }         // Validation Results         for (i = 0; i < events.length; i++) {            events[0] ();        }

First look at the above code, have JS development experience of people are certainly familiar, but some people know, some people do not know. According to the above code, loop through the events array and execute the functions in the array elements, what number will the 10 functions print? The answer is: All will output "10". Let's explain why:

When each function is generated/created, the system assigns it a variable environment, which also includes the data of the closure. However, when multiple environments are common with a closed packet of data, it is a reference to the relationship, which is the focus. References, not duplicates. If this common data is changed, these common environments are acquired, and the data is changed.

Therefore, when the first function is created, i = = 0, the first function refers to the closure of the value of I is 0, the second function is created, i = = 1, which is, the first, the second two functions applied in the closure of the value of I, are 1. And so on, until the tenth function is created, i = = 9; But in the last step of the For loop, i++ is executed; so i = = 10.

Do you understand?

To change the problem, if you want each function to output a different value, you need to not let each function have a closure--let each function use a separate closure data, not shared. Just say the part of the For loop creation function is modified to:

// Looping create function         for (; i <; i++) {            = (function  (index) {                returnfunction  ( Index) {                    console.log (index);                }            }) (i);        }

At this point, I, as a parameter, passes in the anonymous auto-execute function and assigns the value to the index parameter. The variable environment of this anonymous function preserves index and does not change as I changes. That's the point.

Welcome to follow Weibo: weibo.com/madai01

Part2-----------------------------------------------------------------------------------------------------------

1. Preface

Yesterday wrote "JS Note notes (11)-Browse Tom Uncle's Blog Learning Notes Part1", a simple record of several problems. The focus of part1 is still the problem of creating a function in the last loop, that is, multiple sub-functions are common to a closed packet data. If you feel interested, you can turn it over again.

Continue to finish writing the remaining questions today.

2. Scope Chain

People who learn JS, even beginners know the "prototype chain", but "scope chain", probably a lot of people have not heard of. Most people know or hear about "closures," but there may be a lot of people who don't know that closures are actually linked to the scope chain. If you understand that closures do not begin to understand from the scope chain, then you can only understand the fur of closures.

I also learned from Uncle Tom's blog about the scope chain, before also read a lot of books, are not very clear to expand the concept of scope chain. In fact, the scope chain is simple to understand, the following code:

        var x = ten;         function fn () {            var y =;             return function () {                var z =                + + y + z);            }        }

In the above code, if you want to print the value of the x+y+z, you have to traverse three levels of context or scope, which is similar to the structure of the prototype chain. But in the future, together with the closure of the illustrated white, need a lot of content.

There is no further depth here, and there is a chance to have another detailed introduction later.

3. Two-dimensional chain lookup

As mentioned above, through the scope to find variables, in fact, in the process of looking for variables, is the use of "two-dimensional chain lookup"-"Scope chain" + "prototype chain." Look at the following code:

       object.prototype.x = ten;         function fn () {            var y =;             return function () {                var z =                + + y + z);            }        }

This code is similar to the code shown in the scope chain above, but it passes object.prototype.x = 10; In this sentence, the role of the prototype chain is shown.
Therefore, when looking for variable values, it takes into account both the prototype chain and the scope chain two directions, namely "Two-dimensional chain lookup".

4. Independent scopes can only be created by functions

The second sentence of this sentence is--cannot be created by a block of statements such as If/for. The latter half of the sentence you may know, but it is really the first half of the sentence-The independent scope can only be created by the function (except for the independent scope, the rest is the global scope). Since the independent scopes can only be created by functions, the free variables anywhere in the function are function-level, so the following code does not want to reappear:

5. Nature of implicit global variables
var a = ten= 20;

The above two lines appear to declare two global variables, but according to Uncle Tom, only Var can declare a variable, that is, var a = 10; is the true declaration variable.

The next sentence, B = 20, is actually equivalent to setting a property value for window.

Therefore, the essence of the first sentence is to declare a global variable; the essence of the second sentence is to set a property value for window.

Of course, it is not recommended to use the second sentence form.

6. Function declarations and function expressions are different

There are several ways to define a function in JS, but look at the following code:

fn (); var function () {  // function Expression    //  error }//------fn ();  function fn () {  // Functions Declaration    //  123}

Two functions are defined in such a way that they produce a different result.

Here I did not look at the details, because this is not a lot of use, so there is no deep scrutiny, just made a mark. If you have an understanding of friends, do not let explain.

7.js using a static scope

In Part1, when a function is passed as a parameter, and the latter is returned as a value, the scope of it is passed along with it. That's what we often call closures. And look at the following code:

var x = ten;             function foo () {    alert (x);} (function  (funarg) {    var x =;    Funarg ();     // 10, not

Foo is a function that passes it as a parameter into another function, and, together with it, is the scope of Foo. Foo uses a static scope, where the variable x is statically assigned at the time of delivery and is not affected by the X variable in other environments.
This also applies to functions as return values. As follows:

function fn () {    var x = ten;     return function () {        alert (x);    }} var ret = fn (); var x = +; ret ();    // 10, not

For more information, please follow my Weibo blog.


JavaScript-Read the study notes of Uncle Tom's Blog

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.