Reading notes-You don't know the JS on-closures and modules

Source: Internet
Author: User
Tags closure definition

Closure definition

When a function can remember and access the lexical scope in which it is located, a closure is generated, even if the function is executed outside the current lexical scope.

Take a look at the simplest closure code:

    function foo () {        var a = 2;         // Closed Package        function Bar () {            console.log (a);        }         return bar;    }     // In theory, Foo executes the internal data will be destroyed    . // since the scope of the closure has been maintained    var baz = foo ();     // 2

The bar () function can access the scope of Foo () and, after executing through foo (), returns Bar () and passes it as a value to Baz. When Baz executes, bar () still holds a reference to the scope, and this reference is called a closure.

After this function is called outside the lexical scope, the closure allows the function to continue accessing the lexical scope at the time of definition.

To change an example:

    function Wait (msg) {        // Here is an implicit assignment statement        //var msg = msg;        SetTimeout (function() {            /// a second) the intrinsic function retains a reference             to the external msg Console.log (msg);         );    }    Wait (' Hello World ');

A classic example of a cyclic closure:

     for (var i = 0; i < 5; i++) {        // Internal Reference the same I        setTimeout (function() {            //  5 5 5 5 5        }, + * i)    }

If you add Iife:

     for (var i = 0; i < 5; i++) {        (function() {            /// not internally not accepted to parameter or reference External i            setTimeout (function() {                //  5 5 5 5 5            }, 1000 * i)        }) (i)    }

Finally, Iife expression plus upload parameter, success!

     for (var i = 0; i < 5; i++) {        // each pass in one I        (function(i) {             // recessive assignment var i = i;            SetTimeout (function() {                //  0 1 2 3 4            }, + * i)        }) (i)    }

Of course, it's not too easy to use ES6 's let.

     for (Let i = 0; i < 5; i++) {        setTimeout(function() {            console.log (i);         + * i)    }

  

Module

The module sounds very tall, but with a simple example you can understand what a module is!

    functionmodule () {varA = ' Hello world '; varb = [1, 2, 3]            //Method 1        functionstr () {console.log (a); }        //Method 2        functionarr () {console.log (b); }        //Module Exposure        return{showstr:str, Showarr:arr}}varfn =module (); Fn.showstr (); //Hello WorldFn.showarr ();//[A]

This pattern is called a module in JavaScript. The most common method of implementing module patterns is known as module exposure, here is the variant.

First, module (), as a function, must be called to create an instance of a block. If you do not execute an external function, neither the inner scope nor the closure can be created.

Second, the object returned by the function is the literal syntax. The returned object has a reference to the intrinsic function, the internal data is hidden and private, and the return value of the object type can be viewed as a public API that is essentially a module.

There are two necessary requirements for creating a module:

1. There must be an external enclosing function, and the function must be called once. (Each call creates a new instance)

2. The enclosing function must return at least one intrinsic function in order for the intrinsic function to form a closure in the private scope and to access or modify the private state.

The object with the function attribute is not a real module, and the real module must have a closure function.

The module constructor in the previous example, if it becomes iife, is a simple singleton pattern.

    var singlemodule = (function() {        //...        return  {            //...         }    })();     // Direct use of Singlemodule

  

Module mode another simple but powerful change to use is to name the object that will be returned as a public API:

    varSinglemodule = (function(ID1) {//Get Internal Data        functionID () {console.log (ID1); }        //provides a way to change internal data        functionChange (ID2) {id1=Id2; }        //public Interface        varpublic ={change:change, id:id}returnPublic ; })(' ID '); Singlemodule.id (); //UDSinglemodule.change (' Id2 '); Singlemodule.id (); //Id2

By keeping internal references to public API objects inside the module instance, you can remediate the module instances internally, including adding or removing properties.

Modern modules

Most module-dependent loaders essentially encapsulate this module definition into a friendly API.

    //I can't read it for the time being.    varmodule = (function() {        varModules = {}; functiondefine (name, Deps, Impl) { for(vari = 0; i < deps.length; i++) {Deps[i]=Modules[deps[i]]; }            //Core Code            //The wrapper function is introduced for the definition of the module            //Store module APIs in a list of modules that are managed by nameModules[name] =impl.apply (Impl, deps); }        functionget (name) {returnModules[name]; }        return{define:define, get:get}; })();

Do not understand the above code in the end why, now look at the code to define the module!

Module.define (' Bar ', [],function() {        functionHello (who) {return' Let me introduce ' +Who ; }        return{Hello:hello};    }); Module.define (' foo ', [' Bar '],function() {        varHungry = ' Hippo '; functionAwesome () {Console.log (Bar.hello (Hungry). toUpperCase ()); }        return{awesome:awesome};    }); varBar = Module.get (' Bar '); varFoo = module.get (' foo ')); Console.log (Bar.hello (' Hippo '));//Let me introduce hippoFoo.awesome ();//Let ME introduce HIPPO

Reading notes-You don't know the JS on-closures and modules

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.