JavaScript execution environment, scope chains and closures

Source: Internet
Author: User
Tags closure

First look at this statement:

(function ($) {...}) (JQuery);

1. Principle:

Function (ARG) {...}
This defines an anonymous function with a parameter of ARG

When calling a function, the parentheses and arguments are written after the function, and because of the precedence of the operator, the function itself needs parentheses, namely:
(function (ARG) {...}) (param)
This is equivalent to defining an anonymous function with a parameter of ARG, and calling this anonymous function as a parameter param

and (function ($) {...}) (jquery) is the same, the reason why only use $ in formal parameters is to not conflict with other libraries, so the argument with JQuery
Equivalent

Funtion output (s) {...};

Output (jQuery);

Or

var fn=function (s) {...}; FN (jQuery);

2. Function:

The greatest benefit of this notation is the formation of closures. In (function ($) {...}) (jQuery) functions and variables defined internally can only be valid within this scope.

The concept of private functions and private variables is formed.

Several concepts:

1. Execution environment (execution context):

Each function has its own execution environment, and when the execution flow enters a function, the environment of the function is pushed into an environment stack. After the function executes, the stack pops up its environment and returns control to the previous execution environment.

2. Scope chain (scope chain):

The internal environment of the function can be accessed through the scope chain to all external environments, but the external environment cannot access the external environment, which is the scope

There are only global scopes and function scopes in ES5, and there are no block-level scopes.

(But one more let in ES6, he can guarantee that the outer block is unaffected by the inner block.) That is, the inner block forms a block-level scope, which is a feature of Let.

It is not simple, because in many of the functions nested scenarios, only to understand it deeply, to better analyze. )

3. Closure: Refers to a function that has access to a variable in another function scope

A common way to create closures is to create another function (usually an anonymous function) inside one function.

Another function B, defined inside a function A, will form a closure when B is executed outside of a. At the same time, the B function can still access local variables and functions in the a function.

Cons: Closures carry the scope of the function that contains him, which consumes more memory than other functions. So be careful with closures

function fn () {  var array=[];    for (var i=0;i<10;i++) {     array[i]=function() {        return i;}} return Array;} fn (); // [ƒ,ƒ,ƒ,ƒ,ƒ,ƒ,ƒ,ƒ,ƒ,ƒ]

Our intention is to get each function in this array to return its own index value, but the resulting is that each function returns 10.

A closure holds the local variables, parameters, and other intrinsic functions within the function that defines it, that is, the entire VO in the context of the function execution, not a variable. The function scope chain in the code above holds the FN's active objects, they refer to an I, and when FN returns, the value of I is 10, so each function references the same variable that holds the variable of I. If we want the result we want, we can add another anonymous function to change his parent scope (which should be the scope of creating it) and wrap it up.

function fn () {  var array=[];    for (var i=0;i<10;i++) {     array[i]=function(num) {        return  function() {           return  num;};} (i);} return Array;}

This anonymous function has a parameter num and is the return value. When each anonymous function is called, the variable i is passed in. Because the parameter is passed by value, I is copied to num, and the inside of the anonymous function creates a closure that accesses NUM, which returns to the VO (including the parameters) in the anonymous function, so that each function returns a copy of Num, so that a different value can be obtained.

In fact, to say so much, we need to be familiar with the closure of the two application scenarios, we can better understand the meaning of closure.

One. The return value as a function: The VO of the function environment that defines it can still be accessed as the function return value is executed.

function f () {   var a=1;    return function () {      console.log (a);}  } var g=F (); G (); // 1;

Two. As an argument to a function. When the return value of a function is passed in as a parameter to another function, it is still the VO that accesses the function environment that defines it.

function f () {   var a=1;    return function () {      console.log (a);}  } var g=F (); G (); // 1; function F (FN) {var a=2; FN ();} F (g); // 1

The two small examples above also illustrate that closures can access internal variables and intrinsic functions under the scope of the function that defines it. is actually the whole VO, so also contains the parameters.

About this object

We know that the this object is bound at run time based on the execution environment of the function, in the global function, This=window;

When a function is called as a method of an object, the This= object

The execution environment of an anonymous function is global, so its this object usually points to the window

So if you use the This object or the arguments object in a closure, you must save the object's reference to another variable that the closure can access.

JavaScript execution environment, scope chains and closures

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.