About the function

  1. Function A piece of JS code that is defined once but can be executed or called any number of times
  2. Functions can be assigned variables or passed as arguments to other functions
  3. Because they are objects, they can set properties to call their methods
  4. Js functions are parameterized functions whose definitions include a list of identifiers called parameters that act like local variables
  5. The function call provides the value of the argument to the parameter
  6. A method called a bit object if the function mounts another object as an attribute of the object
  7. Js functions can be nested within other functions so that they can access any variable closure in the scope in which they were defined

There are two phases of a function: definition phase Call phase

    //1. Define the phase
        // declarative functions (named functions)
        function fn(){}
        // The assignment function
        var fn=function(){}
        
     //2. Call phase:
        // The two methods of defining functions are different, but they are called the same way.
        // Declarative functions can be called before or after definition;
        fn()
        function fn(){
                console.log(1)
        }
        fn()
                             // Assignment functions can only be called after definition
        fn()                 //fn is not a function
        var fn = function(){ // a simple assignment;
                console.log(1)}Copy the code

Es5 es6

Parameter (top) : ~ that is, a variable defined inside a function (local variable) + Can only be used inside the function but can not be used outside the function + The value of the parameter is determined by the argument passed to the function when the function is called.

Function parameters:

       // Common parameters:
        function fn(a,b){
            console.log(a,b)
        }
        fn(10.20)
       // Use a variable to pass parameters.
        var m=10;
        var n=10;
        function fn(a,b){
            console.log(a,b)
        }
        fn(m,n)
Copy the code

Number of parameters (that is, parameters and arguments)

1. The two parameters correspond to each other

  1. Many arguments (below)Arguments. length + + the arguments are not accepted in the function body, so they cannot be used directly
  2. Multiple parameters (top)The length of the argument is the length of the function. The length of the argument is the length of the function.
Function default parameter values
        // Check if a parameter ==undefined
        function makeKing(name){         // The default value can be set here
                neme = (typeofname! = ="undefined")? name:"cdd";
                return `king ${name} aa`
        }
        console.log(makeKing())           //king cdd aa
        console.log(makeKing("Louis"))    //king Louis aa
        //var area = (width=1, height=1) => width*height ES6
Copy the code
Object arguments are more common in VUE JQ where function arguments are objects
 var opt = {
            width: 10.height: 10
        }
        function area() {
            this.width = opt.width || 1;
            this.height = opt.height || 1;
            return this.width * this.height
        }
        console.log(area(opt));   / / 100
Copy the code
Omit parameters, the default value | | short circuit
        function sub(a, b) {
            a = a || 0;
            b = b || 0;
            return a - b;
        }
        console.log(sub(5.1)); / / 4
Copy the code
When the function returns an object
  function Robot(name) {
            this.name = name
        }
        Robot.prototype.init = function() {
        return {
                say: function () {
                console.log('My name is ' + this.name)
                }.bind(this),
                dance:  function(danceName) {
                console.log('My dance name is ' + danceName)
                }
        };
        }
        var robotA = new Robot('A');
        robotA.init().say(); // "My name is A"
        var robotB = new Robot('B');
        robotB.init().say(); // "My name is B"
Copy the code

arguments; A collection of all arguments, belonging to an array of classes;

Arguments each function in js does not include the arrow function and has access to a special variable called arguments. This variable is maintained so arguments passed into this function is built-in and can be used within the function without declaration; The arguments variable is not an Array syntactically it has the length of an Array but it does not inherit from array. prototype and is actually an object so you cannot use standard Array methods like push pop… Although it’s okay to use a for loop just to make the array method work better it’s better to turn it into a real array

 // Convert to an array
    // Create a new array containing all the elements of the arguments object
    Array.prototype.slice.call(arguments);

    function fn(a,b){
        for(var i=0; i<arguments.length; i++){console.log(arguments[i])
        }
        }
        fn(10.20)     / / 10 20
Copy the code

Arguments objects are only defined in the body of a function. The Arguments object is technically not an array, but it has numeric properties and length properties. The main purpose is to determine how many arguments are passed into the function and it can refer to unnamed arguments plus length properties Plus polish two attributes to refer to the anonymous function itself

Return function?

  function fn(){
              return 10*10    //return the code on the right is returned; Note: Return does not equal output
              console.log(10) // The code after return is not executed;
        }
        fn()                    
        console.log(fn())
        return false          / / for on... The thing that comes out blocks the default event

        //1. Terminate the function after the return code is not executed
        //2. Give the function a return value; The + code to the right of the return allows the function to complete with a result
            //* return value of ruturn is undefined
            //* the value returned by ruturn is undefined
            //* If there is something after return, the function returns the same value.
            //* If you write return but there is nothing behind it, the function returns undefined
            //* Multiple ruturns execute only the first layer of the code will not execute

        / / see the demo
        // Return value:
        function f4(a,b){ 
                return a+b
        }
        var rel=f4(10.30)      // There is a variable rel assigned here
        console.log(rel)       //40 assigns a value to a variable, output the variable to view;
        console.log(f4(10.30)) // Call view directly when output;
Copy the code

This in the function refers to:

Note: in the functionthisPointing, has nothing to do with the definition of the function, just look at the call of the function;1.Global call:this->windowThe function name ()2.Object call:this-> whoever is in front of the dot is the object. Function ()var obj={
                           name:'Ming'.fn:function(){
                                   console.log(this)//obj
                           }
                        }
                        obj.fn()
                3.Timer processing function:this->window   
                        setTimeout/clearInterval(function(){},20);
                4.Event handlerthis-> Event source (who has the event) box. Event =function(){}
                5.Self-executing functions:this->window
                        (function(a){
                           console.log(this)
                        })(10)
                6.Arrow function doesn't have anythis, histhisTo the context, that is, the external scopethis
                        var a=() = >{
                                console.log(this)}7.constructionalthis-> Current instancefunction Person(name,age){ 
                                console.log(this) 
                                this.name=name 
                        }
                       var p1=new Person('little red'.10) 
Copy the code

Modify this to point to

Call () syntax: function name.call ()1The parameter is the his reference of the function you want to change: do not write or writenullforwindow; The second argument starts: passing arguments to the functionvar obj={'name':'Ming'} fn.call(obj) indicates that the internal function of the fn function is executedthisOnclick =fn.call() can't set call here; Apply () syntax: function name.call ()1The parameter is the function you want to changethisPoint; The second argument is an array, each of which in turn passes the fn.call(obj,[) argument to the function.10.20.30])
                        
                        
        bind()
                says(say){
                setInterval(function(){
                        console.log(this.tyep + "say" + say)
                }.bind(this),1000)}// Bind is different from call and apply. Call and apply change this at the same time as this
         // Bind to this does not execute immediately, but returns a new binding function that needs to be executed again
        

Copy the code
Call (),apply(),bind()
Call () syntax: function name. The first argument to call() is the his reference of the function you want to change: do not write or writenullforwindowThe second argument starts: passing arguments to the functionvar obj={'name':'Ming'} fn.call(obj) indicates that the internal function of the fn function is executedthisOnclick =fn.call() can't set call here; The first argument to call() is the his reference of the function you want to change; The second argument is an array, each of which in turn passes the fn.call(obj,[) argument to the function.10.20.30])
bind ...
Copy the code

Arrow function

Arrow functions can’t use arguments super and new.target. They can’t use constructors. In addition, constructor pages don’t have portoType 4 is an abbreviation for a function expression (i.e., an assignment function) that has no effect on declarations

grammar

Function ()=>{} // this is the context of the arrow function’s outer scope The +1 arrow function is not affected by call/apply/bind, which means that the arrow function cannot change the this // arrow function, which was defined at the time it was defined, and no method can change it

// the arrow function does not have this variable

// If there are no line arguments or more than two line arguments, the parentheses must be given

// Add () //({a:1,b:2}) // Otherwise you must write // When you omit {}, the function will return automatically

// If you pass an argument, If no argument is passed, the default value // // is used to write the parameter = default. Arrow functions can also set the default value. // If you set the default value for arrow functions, you also need to write parentheses for an argument

This program is too lazy to continue writing… If there is an error or not precise place, please leave a comment, very thank you, to the author is also a kind of encouragement.