Application of JS function---Immediate execution of functions, global pollution, closures, sandboxes, recursion

Source: Internet
Author: User

First, immediately execute the function---iife
    • Perform a centralized representation of the function immediately:

    • Features of the immediate execution function:

Second, why does JS global pollution cause global pollution?
    • JS has no block-level scope, the variables defined outside the function are global variables;

    • Too many global variables will weaken the flexibility of the program, increase the coupling between modules, multi-person collaborative development will lead to variable conflict, resulting in environmental pollution.

      • Coupling degree: That is the dependence between the modules: control relation, call relation, data transfer relation;
      • Dividing module guidelines: cohesion-poly low coupling
How to solve the global pollution? 1. Namespace 2. Execute the function immediately (the variable created inside is a local variable)
(function(){})()(function(){}())!function(){}()var=function(){} ()
Three, closure 1. The concept of closures
    • Generalized closures : variables are declared inside the function and cannot be accessed outside the function, simulating block-level scopes, i.e. generating closures
      • All functions in JS can form a closed packet.
    • narrow closure : Closure model (a function, as the return value of another function)

    • Closures are actually made up of two parts:
      • Function Body: Code of the function
      • Environment in which the function is located: Scope chain
    • Synthesis: The function body and the function of the environment, become a closure

2. Main Line: functionRegardless of the environment in which the call is to go back to the creation of the function of the environment to execute 3. Closure function:
    • Addressing global pollution

    • Protection of variables within functions; there is no way to access the variables inside the function except for the return function

4. Classic Closure model
    • Can be simply understood as a function as the return value of another function, so that there is an inner layer function, and the outer function;

    • Outer function: Define variables (protect against variables)

    • The inner-layer function returned by the return value: The method that defines the action variable

    • The closure model is as follows:

<Script>    varFn= function(){        varNum= Ten;                return {            F1: function(){}            F2: function(){}        }    };        varTemp= fn();        //Call F1, F2 method    Temp.F1();    Temp.F2();</script>
4. Closure malpractice (memory leak)---> Resolution: inner function = null
    • The variables defined by the outer layer function of the closure are always present and will not be released automatically;

    • Because the inner function always refers to the variables defined in the outer function, and each operation variable of the inner layer function is based on the variables of the outer function.

    • To manually free up memory consumption :内层函数 = null

Iv. Sandbox (a form of embodiment of closures) 1. Sandbox mode
    • function self-invocation

    • To register a property or return variable with window

    • The classic sandbox mode is as follows:

<script>(function{    // 定义变量,及一些列js逻辑    var=‘‘;    window.main= main;  或  return main;})(window)</script>
    • In jquery, sandbox mode is used, as follows:
(function{        window.jQuery=window.$= jQuery;    return jQuery;})();
2. Sandbox's role:
    • Variable isolation, protection variables (variables defined within the sandbox, not accessible outside the sandbox)

    • Avoid global pollution

3. Iife Immediate Execution function
(function(){})()(function(){}())!function(){}()var=function(){} ()
V. Function recursion 1. Simply understand recursion: function yourself---> Call yourself 2. When to use recursion: the function needs to call itself multiple times, nesting itself 3. How do I write a recursive function (3 points)?
      1. Classified into thought: Find out the law and summarize the relationship between the former and the latter
      1. Critical condition: Find critical value, stop recursion
      1. Retrun the invocation of its own function
4. Recursive Correlation algorithm implementation:
    • Recursive implementation of the rabbit sequence (Fibonacci-cut series)
<  script    >  function  fn3  (m) { if  (M ===  1  Span class= "OP" >| |  M ===  2 ) { return 1   }  return  fn3  (M-1     ) +  fn3  (M-2 )  }  console . log  (fn3  (20 ))  <  /SCRIPT>   
    • Fibonacci-Cut sequence optimization "cache"
<Script>    varCache= {};    function Fn4(m){        if(Cache[m]){            returnCACHE[M];        }        if(M=== 1 ||M=== 2){CACHE[M]= 1;            return 1;        } Else {            returnCACHE[M]= Fn4(M-1)+ Fn4(M-2);        }    }    Console.Log(Fn4( $));</script>
    • Recursion: Factorial
<script>    functionfn2{        if<=1{            return1;        }        returnfn2(m-1* m;    }    console.log(fn2(3));</script>
    • Recursion: The second party
<  script>  function  fn1  (M N) { if  (n ===  0 )  {  return  1   }  return  fn1  (M,  n - 1 ) *  m;  }  console . log  (fn1  (2   4 )) Span class= "OP";  <  /SCRIPT>  
5. Recursive---> Robust code in strict mode
    • Simple recursion in non-strict mode
<Script>    varFn= function(m){        if(M<= 1){            return 1;        }        return fn(M-1)*M;    }    varFn1=Fn;Fn= NULL;    Console.Log(fn1(3));  //Error</script>
    • Robust recursion in non-strict mode

      • arguments.calleePointer to a function that is executing
<Script>    varFn= function(m){        if(M<= 1){            return 1;        }        return arguments.callee(M-1)*M;    }    varFn1=Fn;Fn= NULL;    Console.Log(fn1(3));  //6</script>
    • Strict mode, not allowed arguments.callee , robust code is as follows:
<Script>    varFn1= function fn(m){        if(M<= 1){            return 1;        }        return fn(M-1)*M;    }    varFn2=Fn1;Fn1= NULL;    Console.Log(fn2(3));</script>

Application of JS function---Immediate execution of functions, global pollution, closures, sandboxes, recursion

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.