当前位置:网站首页>JS deep understanding of functions

JS deep understanding of functions

2022-06-24 18:36:00 Brother Mengfan

Catalog

One 、 Declaration of functions

1.1、 Custom function

1.2、 Function expression ( Anonymous functions )

Two 、 Function call

2.1、 Custom function call

2.2、 Function expression call

2.3、 The difference between a custom function call and a function expression call

3、 ... and 、 Function parameter

Four 、 Return value

5、 ... and 、 Internal properties of a function

5.1、arguments

5.2、this

6、 ... and 、 Function method

6.1、call()

6.2、apply()

6.3、call() and apply() Application

6.3.1、 Find the largest element in the array

6.3.2、 Convert a pseudo - class array to a real array

6.3.3、 Array append

6.3.4、 utilize call and apply Do inheritance

6.4、bind()

7、 ... and 、 Immediate execution function

7.1、 Definition grammar

7.2、 Execute the function application immediately


One 、 Declaration of functions

There are two ways to declare functions : Custom functions and function expressions .

1.1、 Custom function

Grammar format :

        function  The name of the function ( parameter list ) {
             The body of the function 
            [return  value ]
        }

Be careful :

(1)function Keywords that are declarative functions must be lowercase ;

(2)function Keyword must be followed by function name , Function names generally use the verb , Need to conform to naming rules ;

(3) The function name is followed by a pair of parentheses , Parentheses followed by a pair of braces , Inside the braces is the function body .

1.2、 Function expression ( Anonymous functions )

Grammar format :

        var  Reference function name  = function( parameter list ) {
             The body of the function 
            [return  value ]
        }

Be careful :

(1) To declare a function as a function expression, you still need to use function keyword ;

(2)function Keyword followed by a pair of parentheses , Parentheses followed by a pair of braces , Inside the braces is the function body ;

(3) Since this defined function has no name , So you need to assign a function to a variable .

Two 、 Function call

Depending on how the function is declared, the way the function is called is slightly different .

2.1、 Custom function call

Use the function name to call

        //  Declare functions  
        function myFunction() {

        }
        //  Call function  
        myFunction();

2.2、 Function expression call

You need to call... By function variable name

        //  Declare functions 
        var myFunction = function() {

        }
        //  Call function  
        myFunction();

2.3、 The difference between a custom function call and a function expression call

    <script>
        fn1();

        function fn1() {
            console.log('fn1');
        }

        fn2();// Report errors 
        var fn2 = function() {
            console.log('fn2');
        };

    </script>

difference :

(1) If it is a function declared by a user-defined function , You can call... Before and after you declare a function statement ; If it is a function expression to declare the function , Can only be called after a declaration statement , Cannot call... Before a statement is declared .

(2) For functions declared in a custom function mode , Use Function name To call ; For functions declared in the form of function expressions , You need to go through functions Variable name To call .

3、 ... and 、 Function parameter

Because some values inside the function are not fixed , We need to get different results according to the different values passed during the call , At this time, we need to
To use parameters . Parameters can be divided into formal parameters and actual parameters .
Shape parameter : Used to receive the value passed in when the function is declared , Formal parameters do not need to use var Keyword declaration .
Actual parameters : The actual data passed to the function in parentheses when calling the function .
Grammar format :
    function  The name of the function ( Parameter list ){ 
         The body of the function      
    }
     The name of the function ( Argument list );
According to the matching of formal parameters and actual parameters , The results are not the same , See the table below :

  Example :

    <script>
        function add(a, b) {
            console.log(a, b);
            return a + b;
        }

        var result = add(2, 3); //2 3
        console.log(result); //5

        result = add(4, 6, 9); // 4 6
        console.log(result); //10

        result = add(5); //5 undefined
        console.log(result); //5+undefined=NaN
    </script>

Running results :

  Be careful :

(1) Formal parameters do not need var Declare variables , Otherwise, an error will be reported ;

(2) Function declarations can be with or without parameters ;

(3) When declaring a function, the formal parameters are in parentheses , The default value of the formal parameter is undefined;

(4) When calling a function, the arguments in parentheses are ;

(5) Multiple parameters are separated by English commas ;

(6) When the number of real participating formal parameters does not match, the result is unpredictable , So try to match .

Four 、 Return value

For some functions , After execution, the execution result will be returned to the calling function . In this case, you need to pass through the function body return
Statement to return data to .
Grammar format :
        function  Function name ( Parameter list ) {
             The body of the function ;
            return  sentence 
        }

Example :

    <script>
        function sub(a, b) {
            return a - b;
        }
        var result = sub(3, 1);

        console.log(result); //2

        function fn(s) {
            console.log(s);
            return;
        }

        result = fn('hello'); //hello

        result = fn(); // undefined
    </script>

Be careful :

(1) When the function executes to return When the sentence is , Will end the function execution and return the specified value ;

(2) If the function does not return a value , There can be return sentence , but return It cannot be followed by other values ;

(3) If the function does not return sentence , The value returned is undefined.

5、 ... and 、 Internal properties of a function

5.1、arguments

stay JavaScript The function of arguments Property encapsulates the arguments of the function .

arguments explain :

(1)arguments Is a pseudo array object , It is not an array type , You can use instanceof Operator view ;

(2) When a function is called , The arguments passed are stored in arguments in ;

(3) It can be done by arguments Object's length Property to get the number of arguments ;

(4)arguments[0] Represents the first argument ,arguments[1] Represents the second argument , And so on ;

(5)arguments There is one of them. callee attribute , It is a function object , Point to the currently used function ;

(6) Only functions have arguments object , And each function has this built-in arguments.

Pseudo array description : Pseudo arrays are not really arrays

(1) Pseudo array Having an array lenght attribute ;

(2) Pseudo array It can be stored by index ;

(3) Pseudo array Some methods without real arrays pop()、push() etc. .

Example :

    <script>
        function add(a, b) {
            // console.log(arguments);// It stores all the passed arguments 
            // console.log(typeof arguments);//object
            // console.log(arguments instanceof Array); // false
            // console.log(arguments instanceof Object);// true
            // console.log(arguments.length);//8
            // console.log(arguments[5]);//7

            //  Implement simple addition 
            var sum = 0;
            for (var i = 0; i < arguments.length; i++) {
                // console.log(arguments[i]);
                sum = sum + arguments[i];
            }
            console.log(sum);//44

        }

        add(2, 3, 4, 5, 6, 7, 8, 9);
    </script>

5.2、this

this Itself is JavaScript One of the keywords in , go by the name of this The thing of means Have The object of the current code . In the letter
Number of calls , Depending on how the function is called ,this The objects pointed to are also different .
Example :
    <button> Button </button>
    <script>
        // this  Point to the problem   In general this Finally, it points to the object that calls it 

        // 1、 In global scope or ordinary function this Point to global object window( Pay attention to the... In the timer this Point to window)
        console.log(this); //window

        function fn() {
            console.log(this); //window
        }

        fn();
        window.setTimeout(function() {
            console.log(this); //window
        }, 1000)

        // 2、 Who calls... In method calls this Point to the who 
        var obj = {
            say: function() {
                console.log(this); //obj
            }
        }
        obj.say();

        var btn = document.querySelector('button');
        btn.addEventListener('click', function() {
            console.log(this); //btn
        })

        // 3、 In the constructor this Point to an instance of a function 
        function Fun() {
            console.log(this); //this Pointing to fun Instance object 
        }
        var fun = new Fun();
    </script>

Be careful :

(1) In global scope or ordinary function this Point to global object window( Pay attention to the... In the timer this Point to window);

(2) Who calls... In method calls this Point to the who ;

(3) In the constructor this Point to an instance of a function .

6、 ... and 、 Function method

6.1、call()

Use call() Method , You can write methods that can be used on different objects , no return value .
Grammar format :
 The name of the function .call();

Example :

   <script>
        window.color = 'red';
        var obj = {
            color: 'blue'
        }

        function show() {
            console.log(this.color);
        }
        show(); // red

        show.call(this); // red
        show.call(window); // red
        show.call(obj); // blue


        function add(a, b) {
            return a + b;
        }

        //console.log(window)

        var result = add(2, 3);
        console.log(result);
        //  adopt  call()  Method to call the function 
        result = add.call(this, 1, 8);
        console.log(result); //9

        result = add.call(window, 2, 5);
        console.log(result); //7

        result = add.call(add, 3, 4);
        console.log(result); //7
    </script>

Be careful : When using the function call() Method call , The first argument to the method is the function object , If there are parameters , From The second position starts with... In turn .

6.2、apply()

adopt apply() Method , You can write methods for different objects , no return value .
The grammar is as follows :
 Function name .apply();

Example :

    <script>
        window.color = 'red';
        var obj = {
            color: 'blue'
        }

        function show() {
            console.log(this.color);
        }
        show(); // red
        show.apply(this); // red
        show.apply(window); // red
        show.apply(obj); // blue

        console.log('------------------');

        function add(a, b) {
            return a + b;
        }

        var result = add(2, 3);
        console.log(result);
        result = add.apply(this, [1, 3]);
        console.log(result);
        result = add.apply(window, [4, 5]);
        console.log(result);
        result = add.apply(add, [4, 6]);
        console.log(result);

        console.log('----------------');

        var color = 'green';


    </script>

Be careful :

(1)apply() The application and call() There is no difference in method , You can change the reference image through the first parameter .

(2)apply() Method needs to encapsulate the arguments into an array and pass them uniformly . The first argument is the function object , The second parameter is the array , It encapsulates the parameters .

    <script>
        function print() {
            'use strict'; //  Specify strict mode 
            console.log(this);
            console.log(this.color);
        }

        // print.call(null);
        //print.apply(undefined);
    </script>

Be careful :

(1) In strict mode , The function always points to the specified value ;

(2) In a non-strict mode , If you use call() perhaps apply() Method , Pass in null perhaps undefined Will be converted into a global window object .

6.3、call() and apply() Application

6.3.1、 Find the largest element in the array

    <script>
        var arr = [5, 20, 8, 51, 13];
        //  Find the largest element in the array 
        var maxVal = Math.max(arr);
        console.log(maxVal); //NaN
        var maxVal = Math.max(5, 20, 8, 51, 13);
        console.log(maxVal); //51


        maxVal = Math.max.apply(this, arr); //this=Math.max
        console.log(maxVal); //51
        maxVal = Math.max.apply(this, [5, 20, 8, 51, 13]); //this=Math.max
        console.log(maxVal); //51
    </script>

6.3.2、 Convert a pseudo - class array to a real array

    <script>
        function add() {
            console.log(arguments); //Arguments(3)
            console.log(arguments instanceof Array); //false

            // Array.prototype Prototype   slice Copy 
            var arr = Array.prototype.slice.apply(arguments);

            console.log(arr); //Array(3)
            console.log(arr instanceof Array); //ture
        }

        add(1, 2, 3);
    </script>

6.3.3、 Array append

<script>
    var arr = [];
    Array.prototype.push.apply(arr, [1, 2, 3, 4, 5]);
    console.log(arr);

    Array.prototype.push.call(arr, 4, 5, 6);
    console.log(arr);
</script>

6.3.4、 utilize call and apply Do inheritance

    <script>
        function Animal(name, age) {
            this.name = name;
            this.age = age;
            this.show = function() {
                console.log(this.name, this.age);
            };
        }

        function Cat(name, age) {
            //  Inherit 
            Animal.call(this, name, age);
        }

        var cat = new Cat(' Persian cat ', 3);
        cat.show(); // Persian cat , 3

        function Dog(name, age) {
            //Animal.apply(this, [name, age]);// Sure 
            Animal.apply(this, arguments);
        }

        var dog = new Dog(' Shapi dog ', 2);
        dog.show();
    </script>

6.4、bind()

bind() The method is ES5 New method , The main function is to bind a function to an object , And there is a return value , This return
The return value is a function .
Example :
<script>
    function fun(y) {
        console.log(this);
        return this.x + y;
    }
    var obj = {
        x: 2
    }
    //console.log(fun(3));
    var fn = fun.bind(obj);//bind() Returns a new function fn

    console.log(fn(4));
</script>
Be careful :bind The first parameter of the method is also an object .
Functional programming technology ( The function is coriolized ):
<script>
    function getConf(color, size, other) {
        console.log(color, size, other);
    }
    var fn = getConf.bind(null, '#ff0000', '500px');
    fn('scrollTop');
    fn('display')
</script>
explain : have access to bind() Method to generate a new function object after binding , You can specify some default parameter items in this function object , Then we can receive the customized parameter items through the new function object . This reduces the transfer of developer parameters . Of course, we can also override the default parameter items with the parameters in the customization , So as to realize the application of the framework .

7、 ... and 、 Immediate execution function

The procedure of using the function is to declare first and then call , To execute this function . But in some cases , We need to declare this function , This function should be executed immediately . You need to execute the function immediately .
stay IIFE( Self executing functions ) Specified in the , parentheses () Follow the function , Means to call this function .
The so-called immediate execution function means that it will be executed immediately after the function is defined . The immediate execution function is an anonymous function .

7.1、 Definition grammar

    (function(){ 
         The body of the function ; 
    })(); 

     perhaps 

    (function(){ 
     The body of the function ; 
    }());
Be careful : The immediate execution function is defined in a pair of parentheses , The last pair of parentheses means that the function is called .
Example :
<script>
    function fn(a) {
        console.log('hello ' + a);
    }
    fn('hi');

    //  Immediate execution function 
    (function(){
        console.log('world')
    })();
    (function () {
        console.log('hi')
    }())

    var r = (function (a, b) {
        console.log(a, b);
        return a + b;
    })(1, 2);
    console.log(r);

</script>
Be careful :
(1) Parameters can also be passed in immediate execution functions , Just write the parameter in the calling pair of parentheses .
(2) When writing multiple immediate execution functions , The semicolon behind cannot be omitted .

7.2、 Execute the function application immediately

.1、 Every time you call add, Both return plus 1 The number of ( The initial value is 0
    <script>
        //  demand : Every time you call  add, Both return plus  1  The number of ( The initial value is  0)
        // 1.  Use the previous method to realize 
        function add() {
            return ++add.count; //  to  add  The function object specifies a custom attribute  count,  For sharing data 
        }
        add.count = 0;
        console.log(add()); //1
        console.log(add()); //2
        console.log(add()); //3

        // 2.  Use immediate execution functions to implement 
        var rs = (function() {
            var count = 0;
            //  A variable is declared in the immediate execution function 
            return function() {
                return ++count;
            };
        })();
        console.log(rs()); //1
        console.log(rs()); //2
        console.log(rs()); //3
    </script>

2、 The following procedures exist , See what happened , How to solve

<script>
    function fn() {
        var arr = [];
        for (var i = 0; i < 5; i++) {
            arr[i] = function() {
                return i;
            }
        }
        return arr;
    }
    var f = fn();
    console.log(f);
    console.log(f[0]());
    console.log(f[1]());
</script>

Use execute now function

  <script>
        function fun() {
            var arr = [];
            for (var i = 0; i < 5; i++) {
                (function(n) {
                    arr[n] = function() {
                        return n;
                    }
                })(i);
            }
            return arr;
        }
        f = fun();
        console.log(f);
        console.log(f[0]());
        console.log(f[1]());
        console.log(f[4]());
    </script>

原网站

版权声明
本文为[Brother Mengfan]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202211333166550.html