JavaScript first (three)--------functions, closures, immediate execution functions

Source: Internet
Author: User

Functionsometimes our code repeats a lot of times, programming is called coupling, but programming to pay attention to high cohesion, weak coupling. Functions are present to bring together multiple repetitions. Defined

    Function Primitives: function declarations (functions), function names, parameters (formal parameters, arguments), return values.

1. First, the function is named using a small camel style, that is, the first word lowercase, followed by the first letter of the word capital, such as function Onenumber () {}

2. function expression inside function expression, anonymous function expression

var a = function lala () {}//functional expression var b = functions () {}//anonymous function expression

For ease of use and convenience, we have basically followed an anonymous function expression, called a function expression.

return value

  Function One: Return function final execution result

   Role two: termination function

  

function Scope

    the range of variables and functions in effect is called scope, scopes are divided into global scopes and local scopes. When accessed, the inside of the scope can be accessed outside the outside of the inaccessible inside.

   [[scope]]: Each JavaScript function is an object, some properties of the object we can access, but some can not, these properties are only accessible to the JavaScript engine, [[scope]] is one of them.

[[scope]] refers to what we call a scope, where a collection of runtime contexts is stored.

   Scope Chain : The collection of execution period context objects stored in [[scope]], which is a chained link and we call this chain link a scope chain.

   Run -time context: When the function executes, an internal object called the execution period context is created. An execution period context defines the environment at which a function executes, each time a function executes to produce a corresponding execution

The text is unique, so calling a function multiple times causes multiple execution contexts to be created, and the execution context is destroyed when the function finishes executing.

Pre-compilation

      JS run three steps: syntax analysis, pre-compilation, start execution

imply global Variables

     A variable that does not declare a direct assignment within a function is called a global variable, can be called globally, and a global variable is a property on a window that can be called by Window.name.

precompiled four-part song

1. Create an Ao object (execution context object)

2. Find the function declaration and the variable declaration in the function, and assign the value undefined

3. Assignment (formal parameter and argument unification)

4. Function body assignment to the corresponding AO attribute

  Give me a chestnut.

    function fn (a) {        console.log (a);        ? Unction A () {}        var a = 123;        Console.log (a);        123        function A () {}              Console.log (a);        123        Console.log (b);        Undefined        var b = function () {};              Console.log (b);          function () {}        Console.log (d);         Function d () {}        function D () {}    }    fn (1);

      First, the execution period context is generated, then the function declaration and the variable declaration are a,b,d, and the following is the entire precompilation process.

        ----undefined---1--and function A () {}--123

        ----undefined---function () {}

       -----undefined function d () {}

      Finally, the values corresponding to the AO properties are obtained.

The problem of overwriting between function and Var, for example:

         

function Bar () {    return foo;    function foo () {}    var foo = 111    }    Console.log (bar ());   was return from the beginning.

  

function Bar () {    foo = ten;     function foo () {{;    var foo = one;    return foo;    }    Console.log (Bar ());     Each foo was assigned a value of 11 and was return!!.

  

the above is the entire precompilation process

Closed Package

So much has been said that in order to pave the way for closures, closures cause multiple execution functions to share a public variable. So generally if not special needs, try to use less. Easy to pollute global variables.

Give me a chestnut.   

function A () {   function B () {   var bbb  = 234;   Console.log (AAA);   }   var AAA = 123;   return b;  }  A ();    Function B () {}
var demo = a ();
Demo ();

  Finally, we'll find that demo----function B () {},demo () and 123. This is because when B executes the equivalent of a also executes, so that a will destroy the execution context, but B has been sent out and gave the demo, when the demo execution is equivalent to function B () {} execution, resulting in 123. This is the memory leak, the original scope chain is not released caused.

A chestnut to solidify:

function A () {       var AAA = +;      Function B () {          console.log (AAA);          }       return b;    }    var demo = a ();    Demo ();  the results of the work of B have been saved in the demo.

  When a function is defined, it produces an execution context, which has an AAA, and a function B, when B is defined, already contains the work of a, meaning that it already has the execution context of a, and when B executes, it produces its own execution context, and finally when the a function is executed, The function B is returned to the global scope, although a executes and destroys its own execution context, but because of the existence of its internal B function, there is still a full execution context, so the AAA variable inside function A can still be accessed through the demo.

Application of Closures1. Implementing Public variables
     function Add () {         var num = 0;         Function Demo () {            num++;            Console.log (num);            }            return demo;       }      var test = Add ();      Test ();//1      test ();//2

For the chestnuts above, the public variable is num. The Add function returns the demo function, the demo function still has the execution context of the Add function, and each time it executes the test (), it is equivalent to executing the demo function, and each access num is the same

Num variable, so that num is a public variable, in which case an accumulator can be produced using a closure.

2. Do the caching mechanism

  

function test () {           var num = 0;           function A () {              console.log (++num);            }           Function B () {              console.log (--num);            }            return [A, b];    }        var arr = Test ();        Arr[0] ();//1        arr[1] ();//0

    Both A and B functions are return to the outside so that both A and B functions have a closure with NUM, and both A and B perform the same variable, and when a changes num, B's num also changes, and B operates

Num,a num also changes because they point to NUM, which is the same num, which is equivalent to a cache.

One more chestnut.

Function Eater () {   var food = "";   var obj = {       eat:function () {           if (food = = "") {               console.log (' empty ');               } else{                   console.log ("I am eating" + food);                   Food = "";               }           ,       push:function (myfood) {Food               = Mufood           }       }       return obj;   var eater1 = Eater ();   Eater1.eat ();   Eater1.push (' orange ');   Eater1.eat ();

Like the previous chestnut, the Obj object is return to the outside and is received with Eater1. The food that corresponds to Eater1.eat () and Eater1.push () is the same, which is the use of closures to generate a cache mechanism.

   3. Privatization variables

      The understanding of this function requires a first look at the constructor

function Deng () {                var preparewife = "Xiaozhang";                var obj = {                    name: "Laodeng",                    age:40,                    sex: "Male",                    Wife: "Xiaoliu",                    divorce:function () {                        th Is.wife = delete this.wife;                    },                    getmarried:function () {                        this.wife = Preparewife;                    },                    Changeprepare:function (someone) {                    preparewife = someone;                        },                    saymywife:function () {                        Console.log (This.wife);                    }                }                return obj;            }            Deng = Deng ();

  

  Run it and see.

            Deng.saymywife ()         //"Xiaoliu"            deng.divorce ()           //undefined (no return value)            deng.saymywife ()           //True has been removed            deng.changeprepare (' Xiaoxiaozhang ')   //undefined (function has no return value) ********            deng.getmarried ()        // Undefined            deng.saymywife ()         //"Xiaoxiaozhang"            deng.preparewife         //undefined              

 

the variables inside the Preparewife function are not in the global scope, so we can't access them, but all of our operations are done around Preparewife, and they all have access to the variable, so like this can only be done with

This variable generates a closure method, a property, to give access to that variable, so we call it the privatization variable, and we can set the security level of the variable by customizing the interface (various methods).

Execute function immediately

    This type of function is not declared and is freed after a single execution. Suitable for initialization work. For example, some mathematical formula, or some other constant calculation, we do not need to keep it in the global space, this will be very good memory,

was born immediately executes the function.

var x = (function (A, b) {                    return (A + b);            } (1, 2)) x = 3

The immediate function feature is that when the JavaScript engine resolves to this statement, it executes immediately, destroying its execution context immediately after execution. This allows the memory to be freed, and the immediate execution function can have a return value

, as well as formal parameters.

We need to know that the function declaration cannot be executed, only the function can execute, so

function declarations-----> expressions

function Test () {}//functions declaration, not an expression

var test = function (); function expression

We can convert the function declaration into an expression .

The 1.+function Test () {}-----the > + operator so that the function declaration is converted to an expression, you can execute the

2.! function Test () {}------>!

3. (function Test () {}) ()-------> ()

solve closure problems with immediate execution functions

to achieve print 0-9, the results are unexpected .... (There were 10 10). This I think for a long time just figured out, alas, the brain is not enough to use ...

  function Test () {      var arr = [];       < Ten ; i++) {             () {                 Console.log (i + ",");                 }              }              return arr;          }       = Test ();        J < J + +) {Demo[j] ()            ;          } Ten *

What is this for? The output of the 10 is all 10, indicating that I are all the same I, why this, is the function of the execution of the time I already is 10, because the test and arr produced a closure, let's say, each return

go to an arr, but the function is not yet executed, that is, all Arr[i], when the loop is terminated i=10, when function execution time 10 I are added to 10 of the I, is the same I, so the last print out 10 10. Understand the

It? Feel said too popular, I hope you can understand Kazakhstan.

    

If you feel that I have a problem, welcome to put forward, we progress together ha!

  function Test () {         var arr = [];          < Ten ; i++) {            (function (j) {                console.log (j);                } (i))             }             return arr;         }

Using the immediate execution function, each access to the I is not the same, so the print out is 0-9.

Finally, one more chestnut.

          A = +;          Function Demo (e) {             function E () {}                 arguments[0] = 2;             document.write (e);   2 because the formal parameter list changes E to 2             if (a) {                 var b = 123;                 Function C () {}             }             var C;                A = ten;             var A;             document.write (b);  Undefined             f = 123;             Docuemnt.write (c);  function () {}             Docuemnt.write (a);//Ten          }          var A;          Demo (1)          docuemnt.write (a);          document.write (f);

JavaScript first (three)--------functions, closures, immediate execution functions

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.