JS core series: scope of functions

Source: Internet
Author: User
JS core series: scope of functions I. scope)

The so-called scope is: variables are defined in the declared function bodies and any function nested in this function body.

function scope(){    var foo = "global";    if(window.getComputedStyle){        var a = "I'm if";        console.log("if:"+foo); //if:global    }    while(1){        var b = "I'm while";        console.log("while:"+foo);//while:global        break;    }    !function (){        var c = "I'm function";        console.log("function:"+foo);//function:global    }();    console.log(         foo,//global         a, // I'm if         b, // I'm while         c  // c is not defined    );}scope();

(1) The foo variable defined in the scope function can be accessed in the if statement, while statement, and embedded anonymous function. Therefore, the scope of foo is the scope function body.

(2) In javascript, if, while, for, and other code blocks cannot form independent scopes. Therefore, javascript has no block-level scope and only function scope.

However, there is a special situation in JS:

If a variable does not use var declaration, window has this attribute. Therefore, the scope of this variable does not belong to a function body, but is a window object.

function varscope(){    foo = "I'm in function";    console.log(foo);//I'm in function}varscope();console.log(window.foo); //I'm in function

2. scope chain)

The so-called scope chain is: a function body contains nested multi-layer function bodies and defines the same variable in different function bodies. When one function accesses this variable, A scope chain is formed ).

foo = "window";function first(){    var foo = "first";    function second(){       var foo = "second";       console.log(foo);    }    function third(){       console.log(foo);    }    second(); //second    third();  //first}first();

The JS engine places the second scope in the head of the linked list, followed by the first scope, and finally the window object. Therefore, the following scope chain is formed:

Second-> first-> window. At this time, the JS engine searches for the variable foo along the scope chain and finds "second"

When third is executed, third forms a chain of scopes: third-> first-> window. Therefore, the returned result is: "frist"

Special case: with statement

The with statement in JS is mainly used to temporarily extend the scope chain and add the objects in the statement to the scope header. After the with statement ends, the scope chain returns to normal.

foo = "window";function first(){    var foo = "first";    function second(){       var foo = "second";       console.log(foo);    }    function third(obj){       console.log(foo); //first       with (obj){           console.log(foo); //obj       }       console.log(foo); //first    }    var obj = {foo:'obj'};    third(obj);}first();

When third () is executed, an obj object is passed. obj has the property foo. When the with statement is executed, the JS engine places the obj in the header of the original linked list, the scope chain is as follows:

Obj-> third-> first-> window, the searched foo is foo in obj, so the output is: "obj", before and after, all of them are searched along the original linked list, which means that after the with statement ends, the scope chain has recovered to normal.

3. this keyword

In a function, this always points to the owner object of the current function. this always determines its specific point at runtime and its calling object.

This sentence summarizes everything about this. Remember, remember, and remember! (Ps: three important things !)

window.name = "window";function f(){    console.log(this.name);}f();//windowvar obj = {name:'obj'};f.call(obj); //obj

When f () is executed, the caller of f () is the window object, so the output of "window" is"

F. call (obj) is to put f () on the obj object for execution, which is equivalent to obj. f (). In this case, this in f is obj, so the output is "obj"

Iv. Practical Application

Code1:

var foo = "window";var obj = {    foo : "obj",    getFoo : function(){        return function(){            return this.foo;        };    }};var f = obj.getFoo();f(); //window

Code2:

var foo = "window";var obj = {    foo : "obj",    getFoo : function(){        var that = this;        return function(){            return that.foo;        };    }};var f = obj.getFoo();f(); //obj

Code1 and code2 are the best summary of this and scope. If you have any questions about the running results, please discuss them!

Code parsing:

Code1: Run var f = obj. getFoo () returns an anonymous function, which is equivalent to: var f = function () {return this. foo;} f () is equivalent to window. f (), so this in f points to the window object, this. foo is equivalent to window. foo, so f () returns "window" code2: Execute var f = obj. getFoo () returns the same anonymous function, that is, var f = function () {return that. foo;} The only difference is that this in f is changed to that. Before you know which object that is, determine the scope chain of f: f-> getFoo-> window and search for that in the chain. At this time, you can find that refers to this in getFoo, and this in getFoo points to the caller at runtime, from var f = obj. getFoo () indicates that this points to the obj object, so that. foo is equivalent to obj. foo, so f () returns "obj"

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.