JavaScript scopes, anonymous functions, and closures examples (1/3)

Source: Internet
Author: User
Tags anonymous closure

Anonymous functions are functions that have no names, and closures are functions that can access variables in a function's scope.

A anonymous functions

The code is as follows Copy Code

normal function

function box () {//Functions name is box

Return ' TT ';

}

anonymous functions

function () {//anonymous functions, error

Return ' TT ';

}

Self-executing by expression

(function box () {//encapsulated as an expression

Alert (' TT ');

})(); () represents an execution function, and the argument

Assigning an anonymous function to a variable

var box = function () {//Assign an anonymous function to a variable

Return ' TT ';

};

Alert (Box ()); Similar to call mode and function call

Anonymous functions in a function

function box () {

return function () {//anonymous functions in function, resulting in closures

Return ' TT ';

}

}

Alert (Box () ()); Calling anonymous functions

Two Closed Bag

Closures are functions that have access to variables in the scope of another function, and the common way to create closures is to create another function inside one function and access the function's local variables through another function.

code example:

The code is as follows Copy Code

You can return a local variable by closing the package

function box () {

var user = ' TT ';

return function () {//returns box () local variable via anonymous function

return user;

};

}

Alert (Box () ()); Call anonymous function return value directly via box () ()

var b = box ();

Alert (b ()); Another call to an anonymous function return value

The use of closures has an advantage and disadvantage: it is possible to host local variables in memory and avoid using global variables. (global variable pollution causes application unpredictability, each module can call will lead to disaster, so it is recommended to use private, encapsulated local variables).

The code is as follows Copy Code

1. Add by Global variables


var age = 100; Global variables

function box () {

Age + +; The module level can call global variables to accumulate

}

Box (); Executive function, additive

alert (age); Output Global Variables

2. Accumulation cannot be realized by local variables

function box () {

var age = 100; Local variables

Age + +; Accumulation

return age;

}

Alert (Box ()); 101

Alert (Box ()); 101, unable to implement because it was initialized again

3. The accumulation of local variables can be realized by closure


function box () {

var age = 100;

return function () {

Age + +;

return age; Returns the age, which enables the local variable to reside

}

}

var b = box (); Get functions

Alert (b ()); Calling anonymous functions

Alert (b ()); The second call to the anonymous function to implement the cumulative

PS: Because local variable resources returned by the scope of the closure are not destroyed immediately, they may consume more memory. Excessive use of closures can lead to performance degradation, and it is recommended that closures be used when necessary.

Problem: The mechanism of the scope chain results in a problem where any variable obtained by the anonymous function in the loop is the last value.

The code is as follows:

The code is as follows Copy Code

The loop contains anonymous functions.
function box () {

var arr = [];

for (var i = 0; i < 5; i++) {

Arr[i] = function () {

return i;

};

}

return arr;

}

var b = box (); Get an array of functions

alert (b.length); Get the function set length

for (var i = 0; i < b.length; i++) {

Alert (B[i] ()); Output the value of each function, which is the last value 5

}

Analysis: The above example output results are 5, that is, the maximum value of I after the loop. Because B[i] calls anonymous functions, the anonymous function does not perform itself, waiting for the Call, Box () has been executed, I have already become 5, so the final result is 5 5.

  code is as follows copy code

 

///1: Self-executing anonymous function

function box () {

    var arr = [];

    for (var i = 0; i < 5; i++) {

        arr[i] = (functio N (num) {//self-executing

        return num;

       }) (i);         //and parameter

   }

     return arr;

}

var b = box ();

for (var i = 0; i < b.length i++) {

    alert (b[i]);       &nbs P This returns an array that can be printed directly

}

In the 1, we let the anonymous function execute itself, resulting in an array rather than a function, which is ultimately returned to A[i. The 0,1,2,3,4 value is retained in the final b[0]-b[4].

Change 2: Anonymous function, and then an anonymous function.

(the principle is similar to the previous addition of the local variable by the closure, the closure allows the variable to reside in memory)

Because the parameters are different each time the outer function is called. Each time it is invoked, it (the returned nested function) creates a slightly different scope.

That is, each call to the outer function produces a different invocation object in the scope chain. (Scope chain knowledge See this series 2)

The code is as follows Copy Code

function box () {

var arr = [];

for (var i = 0; i < 5; i++) {

Arr[i] = (function (num) {

return function () {//directly returns the value, change 2 into return

return num; Principle and change 1.

}

}) (i);

}

return arr;

}

var b = box ();

for (var i = 0; i < b.length; i++) {

Alert (B[i] ()); This is called by the B[i] () function.

}

In 1 and 2, we execute ourselves by anonymous functions and immediately assign the result to A[i]. Each I, the caller, is passed by value, so the final return is the specified incremented I. Rather than the I in the box () function.

Home 1 2 3 last
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.