JavaScript Sunflower Treasure Pack closure

Source: Internet
Author: User
Tags closure

Closure, the person who wrote the JS script must not be unfamiliar with the word, all said that the closure is the most magical JS in a knowledge point, although in the work, the project will often use ~ but is not you have really enough understanding of it ~ ~

Or is your code appear in the closure, not you deliberately and for the behavior ~ or because it can achieve the effect, but also know that the closure, but the principle does not know?

1000 people have 1000 Hamlet ~ Everyone may have their own understanding of the closure, I am no exception, once n times Baidu has closed the package, but did not really digest this knowledge point, has worked countless times in the use of closures, but do not know why ~ ~

Therefore, I want to understand the closure of my own summary, although a lot of their own understanding, but the summary of the correction, will be more and more good ~ ~

The first is the definition of closures:

    • Wikipedia's definition of closures:
Closures (English: Closure), also known as lexical closures (Lexical Closure) or function closures (functions closures), are functions that reference free variables. This quoted free variable will exist with this function, even if it has left the environment in which it was created. So, there is another argument that closures are entities that are composed of functions and their associated reference environment. Closures can have multiple instances at run time, and different reference environments and the same combination of functions can produce different instances.
    • Book "JavaScript You Don't know" definition of closures: (a book that the person thinks is the best one to explain the closure)
When a function can remember and access the lexical scope in which it is located, a closure is generated, even if the function is actually executed outside the current lexical scope.

The above concept has basically explained the closure is what, this is just a generalization, do not know the person after watching or will not know, so to know the closure or need to discovering the same layer of a layer to understand ~ ~

Give yourself a few questions? Then make a layer of understanding of these questions until you understand them!

    • The environment in which closures occur?
    • The role of closures?
    • Some usage scenarios for closures?
    • What are the drawbacks of closures?

Environment of closures:

Since it is called closures, there is a package word, then must be surrounded by the meaning of the ~ unexpectedly is surrounded, it is definitely in a space, and JS can represent the space is what? is scope, scope and global scope and local scope.

So the environment of the closure should be in the scope, so there must be a closure of the local scope, there is a local scope does not necessarily have closures ~ ~

The role of closures:

There must be a closure of the existence of the value of its existence, then the role of closures to reflect where?

var a = 1; function fn1 () {    //1    var b = 2//B is not defined  // when there is a variable a in the global, we can access/modify the variable at any time in the function fn1, but when I have a variable of 2 in my function fn1, I want to access this b outside, obviously, failed, Because the outer scope is inaccessible to the internal scope;

And the thing to do with closures is that we can access the variable b!

function fn1 () {    var b = 2;     return function () {        return  b;    }} var b = fn1 () (); Console.log (b);   // 2

Obviously, we get the value of B, which is what we want, but why is it possible to get the value of B?

    • In the returned function, we can get the B's worth, because the intrinsic function is accessible to any variable in the outer scope;
    • In the returned function, we return this value, and there will always be a b=2 value in all fn1;
    • After the general fn1 function call, B will be destroyed, but since we call this B in its return function, this B will always exist in memory and will not be destroyed (this is one of the drawbacks of closures, explained later);
    • In this way, we use the principle of closure, the value of B to secretly stole out ~

From the small example above we can know that the function of the closure is to let the outside can not get the variable is worth the place can be successfully obtained these values, although the external function can not get the value of the intrinsic function is JS to its scope of protection, although the closure of the protection of the damage, However, some functions that are not normally implemented are implemented.

Some usage scenarios for closures:

The use of closures is really ubiquitous, although it is possible that you are not aware of it, but can not deny its existence ~

In the closure of some of the actual application of the place, first look at a JS in the closure of the classic small case ~ ~

 for (var i=1; i<=5; i++) {    setTimeout (function  timer () {        console.log (i);   // The result is not the 1-5 we want, but it appears 5 times in a row 6    }, i*1000);}

Why would that be? Because of the scope problem, previously said there is a closure of the scope ~ there is only a global scope, there is only one I in the global, so each change I will just give it a new value;

When the SetTimeout method executes, the loop is finished, so each loop is i++ until the loop is completed and becomes 6;

Because there is no block-level variable in JS, so we can get the value of each I, so we want to create a scope to store the value of the variable i, iife (function self-executing) can create a block-level variable:

 for (var i=1; i<=5; i++) {    (function//2, assign the value of I to J        SetTimeout ( function timer () {            console.log (j);   // 3,j output is the value of I in each loop        }, i*1000);    }) (i)   // 1, each cycle gets the value of I }// execution result    1,2,3,4,5

In this way, we want to achieve the results, said before, JS no block-level variables, if any, is not more simple, ES5 no, but ES6, then with the block-level variable how to achieve:

 for (Let I=1; i<=5; i++) {  // islet    setTimeout (function  timer () {        console.log (i);     }, I* );} // 1,2,3,4,5

In the actual work, we may often release to the JS modular, modular implementation is the use of JS in the closure ~ ~ ~

functionModulefn () {varName = ' Just '; vararr = [A.]; functionNamefn () {console.log (name); }    functionArrfn () {Console.log (Arr.join ("!")); }    return{//Generate closures! An object is returned in the current function, in which there are namefn, and ARRFN, and the variables in Modulefn are in the two functions. namex:namefn, ARRX:ARRFN}}varFoo =Modulefn (); Foo.namex (); //justFoo.arrx ();//1!2!3//with closures, we can get the values in scope! ~~

It is because of this feature of closures, in many scenarios can use the closure of the exhibition skills ~ But, the master use of big strokes is the need to abolish the internal force of ~ ~ and closed the internal force of the package ~ ~ ~

The drawbacks of closures:

    • Because the closure will make the variables in the function are stored in memory, memory consumption is very large, so can not abuse closures, otherwise it will cause the performance of the Web page, in IE may lead to memory leaks. The workaround is to remove all unused local variables before exiting the function.
    • The closure changes the value of the inner variable of the parent function outside the parent function. So, if you use the parent function as an object, take the closure as its common method, and take the internal variable as its private property (private value), be careful not to arbitrarily change the value of the internal variable of the parent function.

Can realize the function is important, but to ensure that the performance is equally important, this one of the take and the house, only in the ongoing project to free the actual combat ~

If you can use the closure of the very familiar, then JS in the Sunflower Treasure Book you also cultivate almost ~ ~

Below is an online closure of the ultimate topic ~ If you can understand, then congratulate you, practice became a sunflower treasure! ~

function Fun (n,o) {  console.log (o)  return  {fun    :function(m) {       return fun (m,n);}}  ;} var a = fun (0);  A.fun (1);  A.fun (2);  A.fun (3); // undefined,?,?,? var b = Fun (0). Fun (1). Fun (2). Fun (3); // undefined,?,?,? var c = Fun (0). Fun (1);  C.fun (2);  C.fun (3); // undefined,?,?,?

The answer will be known since the palace! ~

JavaScript's closure of sunflower Treasure Book

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.