Js study summary (two) function

(A) declare the function

  1. Direct amount (literal) statement
    function f1(){
        ...
    }
  1. Express statement shows
    var f2 = function(){
        ...
    }
  1. Built-in constructor declaration (this way is rare, generally do not, so I will not go into too much)
    var f3 = new function();

(B) call a function

  1. Declare the amount of direct function call
    f1();
    function f1(){
        console.log(111);
    }
    f1();

result:

111
111

Before and after the declaration can be called

  1. Express statement shows a function call
    f2();
    var f2 = function(){
        console.log(222);
    }
    f2();

result:

    异常:f2不是一个方法(原因:js的变量和函数提升)
    222

Only after the first statement calling

(C) and function parameter arguments

After the update

(D) callback function

1. The place where its function in the statement of scope in JS, rather than calling

2. In the function Js is known as the first class citizens, because the function is a special data types js,
JS value to the form handler, then led to JS callback function.

    //1.声明赋值变量a
    var a = 1;
    function f1(f){
        //3.进入f1()方法
        console.log(f);
        //4.声明赋值变量a
        var a = 2;
        //5.执行f()方法,也就是f2()【可以理解为指针或引用】,并寻找f2()声明处并执行
        f();
    }
    function f2(){
        //6.执行f2(),寻找变量a(先找到全局变量a,所以没有找到局部变量a,至于它为什么没有套娃执行和找不到局部a,这是js的运行原理,也就是js作用域链)
        console.log(a);
    }
    //2.将函数名f2传入函数f1内
    f1(f2);

result:

[Function: f2]
1

(V) function closure

Closure variable is a function that can access other functions scope.

Packages are closed:

1. Keep Scope

2. The function of internal and external bridge

    //0.声明赋值全局a
    var a = 2;
    //0.声明方法f1()
    function f1(){
        //1.声明赋值局部a
        var a = 1;
        //2.声明方法f2()
        function f2(){
            //6.发现a,在作用域链中寻找a,首先找到了f1()的局部a,并打印
            console.log(++a);
        }
        //3.终止f1运行并返回f2的指针
        return f2;
    }
    //0.声明并运行f1()
    var f = f1();//4.f能够引用f2()方法,因为f还保留f2()的指针,所以f1()留在内存的数据暂且不能销毁。
    f();
    //5.执行f2(),因为f还保留f2()的指针,所以f1()留在内存的数据暂且不能销毁。
    f();
    //6.同上,因为始终保存着f1()的数据,所以以上修改的f1()的a一直都是一个值。
    f();
    //7.同上
    f();
    //8.同上

result:

2
3
4
5

The reason:
As the operating results are returned f1 f2, and since then the issue of the scope chain and scope of the function itself, lead to the end of the f1 run, can not be destroyed variables, thus creating a closure.

Guess you like

Origin www.cnblogs.com/fpgz99810/p/12227535.html