JavaScript lexical scopes and calling objects

Source: Internet
Author: User

The relationship between Javascript function scopes, calling objects, and closures is very subtle. There are many articles about them, but I don't know why many new users are hard to understand. I will try to express my understanding in a more popular language.
Scope
Functions in Javascript belong to the lexical scope, that is, they run in the scope when they are defined, rather than in the scope when they are executed. This is what the rhino book says. But some people do not know the two things: "Definition" and "execution (called. To put it simply, when function A is "defined", function A () {} is executed when the function is defined, and function A is called () this statement is executed. These two concepts must be clearly divided.
What is the lexical scope (hereinafter referred to as "Scope" unless otherwise specified? It is an abstract concept. To put it bluntly, it is a "range" and scope is the meaning of scope in English. The scope of a function is the "range" of the function when it is defined, that is, the "range" of its outer layer. This "range" contains the variable attributes of the outer layer, this "range" is set to an internal state of this function. When a global function is defined, the "range" of the global function (the outer layer of the function) is set to an internal state of the global function. When a nested function is defined, the "range" of the nested function (outer function) is set to an internal state of the nested function. This "internal status" can be understood as the scope chain. See the following.
As mentioned above, the scope of a function is the "range" when it is defined, so the function scope in Javascript is determined when the function is defined, therefore, it is a static scope, and the lexical scope is also called a static scope.
Call Object
The call object of a function is dynamic. It is instantiated only when the function is called. We already know that when a function is defined, its scope chain has been determined. When the Javascript interpreter calls a function, it adds a new object (called object) to the front of the scope chain. An attribute of the called object is initialized to an attribute named arguments, which references the Arguments object of the function. The Arguments object is the actual parameter of the function. All local variables declared using the var statement are also defined in this call object. At this time, the called object is in the header of the scope chain. The local variables, function form parameters, and Arguments objects are all in the scope of this function. Of course, local variables, function form parameters, and Arguments objects overwrite attributes with the same name in the scope chain.
Relationships between scopes, scope chains, and calling objects
In my understanding, the scope is abstract, and the called object is instantiated.
When a function is defined, it is actually executed by its outer function. The scope chain it determines is actually the call object chain of its outer function. When a function is called, its scope chain is based on the defined scope chain (the call object chain of its outer function) plus an instantiated call object. Therefore, the function scope chain is actually the call object chain. When a function is called, its scope chain (or call object chain) is actually a superset of the scope chain it determines when it is defined.
The relationship between them can be expressed as: scope? Scope chain? Call object.
This is too difficult. For example:
Copy codeThe Code is as follows:
Function f (x ){
Var g = function () {return x ;}
Return g;
}
Var g1 = f (1 );
Alert (g1 (); // output 1
Suppose we regard the global function as a big anonymous function like the following:
(Function (){
// Global scope
})();
The example is as follows:
(Function (){
Function f (x ){
Var g = function () {return x ;}
Return g;
}
Var g1 = f (1 );
Alert (g1 (); // output 1
})();

When a global big anonymous function is defined, it has no outer layer, so its scope chain is empty.
The global large anonymous function is directly executed, and there is only one 'Global Call object' in the global scope chain '.
Function f is defined. At this time, function f's scope chain is its outer scope chain, that is, 'Global Call object '.
Function f (1) is executed, and its scope chain is the new f (1) Call object plus the scope chain when function f is defined, that is, 'f (1) call Object> Global Call object '.
Function g is defined in f (1) and its scope chain is its outer function f (1) scope chain, that is, 'f (1) Call object-> Global Call object '.
Function f (1) returns the definition of function g to g1.
Function g1 is executed, and its scope chain is the new g (1) Call object plus the scope chain of outer f (1), that is, 'g1 call object-> f (1) call Object> Global Call object '.
You can see it clearly.
Closure Closuer
A simple saying of closures is that when nested functions are called outside of nested functions, they form a closure.
The previous example is actually a closure. G1 is defined in f (1), but is executed only after f (1) is returned. It can be seen that one of the effects of closures is that after being returned by nested function f, its internal resources will not be released. When calling the g Function externally, g can access the internal variables of f. Based on this feature, you can write a lot of elegant code.
For example, if you want to make a uniform counter on a page, you can write it like this if you use the closure statement:
Copy codeThe Code is as follows:
Var counter = (function (){
Var I = 0;
Var fns = {"get": function () {return I ;},
"Inc": function () {return ++ I ;}};
Return fns;
})();
// Do something
Counter. inc ();
// Do something else
Counter. inc ();
Var c_value = counter. get (); // now c_value is 2

In this way, a variable I is maintained in the memory, and the value of I cannot be operated directly anywhere else in the program. Only two counter operations can be performed.
In setTimeout (fn, delay), we cannot pass parameters to the fn function handle, but we can bind the required parameters to the fn through the closure method.
Copy codeThe Code is as follows:
For (var I = 0, delay = 1000; I <5; I ++, delay + = 1000 ){
SetTimeout (function (){
Console. log ('I:' + I + "delay:" + delay );
}, Delay );
}

In this way, all the printed values are
I: 5 delay: 6000
I: 5 delay: 6000
I: 5 delay: 6000
I: 5 delay: 6000
I: 5 delay: 6000
Using the closure method, you can easily bind the parameters to be passed in:
Copy codeThe Code is as follows:
For (var I = 0, delay = 1000; I <5; I ++, delay + = 1000 ){
(Function (a, _ delay ){
SetTimeout (function (){
Console. log ('I:' + a + "delay:" + _ delay );
}, _ Delay );
}) (I, delay );
}

Output:
I: 0 delay: 1000
I: 1 delay: 2000
I: 2 delay: 3000
I: 3 delay: 4000
I: 4 delay: 5000
Closure also has a very common feature, that is, when binding Event Callback functions. Similarly, the bound function handle cannot be used as a parameter, but can be used as a closure to bind the parameter.
Summary
The Lexical scopes and scope chains of functions are different. Lexical scopes are abstract concepts, and scopes are instantiated call object chains.
When a function is defined and its outer function is executed.
When a function is defined, its lexical scope has been determined, but it is still an abstract concept and cannot be instantiated.
When a function is defined, it also determines a thing, that is, the scope chain of its outer function, which is instantiated.
When a function is called multiple times, its scope chain is different.
The closure is very powerful. The rhino book is right. After understanding these things, you can claim to be a senior Javascript programmer. By taking advantage of these concepts, you can play with many Javascript design patterns.

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.