7. expand function

Extended Functions

A default value of the parameter function

1. Basic Usage

  1. Before for ES6, can not set the default value of the parameter of the function, the function can only be determined in vivo on the default values ​​and assign it

    //判断y是否存在,不存在则给它默认值 'world'
    function func(x,y){
        y ? y : 'world';
        console.log(x + y);
    }
  2. ES6 allows default values ​​for the parameters of the function, i.e. directly after the write parameters defined **

    • note:
    • Parameter of the function is declared in default, and let not use const Again
    • The default parameter values ​​are lazy evaluation, only when they are needed, will be recalculated
    function func(x,y = 'world'){
        console.log(x + y);
    }
    func('hello');           //helloworld
    func("hello","");        //hello

2. assign default values ​​and deconstruction combination

  1. The default value of the parameter and default values ​​can be used in conjunction with deconstruction assignment

  2. Thoughts: The following two way, what's the difference

    function m1({x = 0,y = 0} = {}){
        console.log(`[${x},${y}]`)
    }
    
    function m2({x,y} = {x:0,y:0}){
        console.log(`[${x},${y}]`)
    }
    • The first written, the default value of the function parameter is an empty object, however, sets the default value of the object deconstruction
    • The second wording, set default values ​​for function parameters, but do not set the default value of the object deconstruction
    m1();                //[0,0]
    m2();                //[0,0]
    
    m1({x:3});           //[3,0]
    m2({x:3});           //[3,undefined]
    
    m1({x:3,y:5});       //[3,5]
    m2({x:3,y;5});       //[3,5]
    
    m1({});              //[0,0]
    m2({});              //[undefined,undefined]

3. The position parameter defaults

  1. See the following example

    function func(x=0,y){
        console.log(`[${x},${y}]`);
    }
    
    func();                  //[0,undefined]
    func(1);             //[1,undefined]
    func(,3);                //报错
    func(undefined,3);       //[0,3]
  2. The second example

    function func(x,y=0,z){
        console.log(`[${x},${y},${z}]`)
    }
    
    func();                  //[undefined,0,undefined]
    func(1)                  //[1,0,undefined]
    func(1,,2)               //报错
    func(1,undefined,2)      //[1,0,2]
  3. Summarized above two examples can be found

    • If the parameter is set to the default value of non-tails, in fact, no way this parameter is omitted, at least have to specify undefined, otherwise an error
    • When the default parameter in the final position, you can not specify
  4. In summary, the parameters have default values, generally in the parameter list of the final surface

4. Function length property

  1. Default parameters specified conditions, length attribute functions will only return there is no default value is the number of parameters

    (function func(x,y){}).length;           //2
    (function func(x=0,y){}).length;     //1

The default parameters scope

  1. Once the set parameter default values, declared initialization function, the parameters will form a separate scope, until the end of the initialization, the scope will disappear. The syntax of this behavior, do not set the default parameter values ​​when it is not appearing

    • The following example:
    var x = 1;
    function foo(x,y=function(){x=2;}){
        var x = 3;
        y();
        console.log(x);
    }
    foo();                   //3
    console.log(x);          //1
    • Analytical Example: In the above example, function parameters form a single scope, within the scope, declares a variable x, y declared variable, the default value is a function of y, the point to the same internal function x the first argument a scope of x. Inside the function, but also a statement x, the variable internal parameter x is not the same scope, so it is not the same variable, so after performing y, x internal functions and external variables of a function of x variables are not changed
    • If after removing var declared inside a function, the function of the first parameter of the internal variables x and x is a function of the same variable, performs Y End () method returns inside x 2
    var x = 1;
    function foo(x,y=function(){x=2;}){
        x = 3;
        y();
        console.log(x);
    }
    foo();                   //2
    console.log(x);          //1

6. Application

  • You can set the default value of certain parameters of the function is a function exception thrown when these parameters are undefined, it will throw an exception
  • Set the default parameter is undefined, explained the parameter may be ignored

Two parameters .rest

  1. ES6 introduced the rest parameters in the form (... variable names). Get extra user function parameters, thereby eliminating the need to use the arguments object

    • Note: You can not have other parameters after the rest, otherwise it will error
    • rest parameter is an array, it is a function of the extra parameters into an array
    • length property function, does not contain rest parameter
    function func(...numbers){
        console.log(numbers);
    }
    func(1,2,3);     //[1,2,3]
    console.log(func.length)     //0

III. Strict Mode

  1. ES5 from the start, internal functions can be set strict mode

    function func(){
        'user strict';
        //code...
    }
  2. ES6 do a little modification, providing that function uses the default parameter values, destructuring assignment, or extended operators, then the internal function can not be set to strict mode, otherwise it will error

    function func(x=10){
        'use strict'
        //...报错
    }

Four .name property

  1. The name attribute function, the function returns the name of the function, this property has long been supported browser, but in the ES6 before it is written to standard

    • note:
    • If an anonymous function assigned to a variable, ES5's name property will return an empty string, the ES6 It will return the variable name is assigned
    • If you have a function assigned to a variable name, whether or ES5 ES6, whose name property returns the original name of the function
    const f = function bar(){}
    f.name;      // bar
    • Examples of Function constructor returns, name attribute is anonymous
    (new Function).name          //annoymous

V. function arrow

1. Basic Usage

  • ES6 allows the use of "arrow" (=>) Defined Functions
var f = v => v;

//等同于
var f = function(v){
    return v;
}
  • If the function does not require parameters or arrow require multiple parameters, you can use a parametric representation of a portion parentheses
var f = () => 5
//等价于
var f = function(){
    return 5;
}

var f = (x,y) => x + y
//等价于
var f = function(x,y){
    return x + y;
}
  • If the arrow direct function returns an object, the object must be added outside the parentheses, otherwise it will error
//报错
let getTempItem = id => {id:id,name:'temp'}

//不报错
let getTempItem = id => ({id:id,name:'temp'})
  • Function can use the arrows and the binding variable deconstruction
let func = {first,lasst} => first + ',' + last

//等价于
function func({first,lasst}){
    return person.last + "," + person.last;
}
  • Callback function can be simplified arrow
  • Function can be used with the arrow rest parameter

2. Use Precautions

  1. this object within the function is defined when the object is located, while you were on when not using

  2. Not as a constructor, that can not be instantiated using new, otherwise an error

  3. Arguments object can not be used, may be used instead of the rest parameter

  4. Yield command can not be used, and therefore the function can not be used Generator function arrow

  5. Arrow function in this, a detailed description

    • Arrow function does not own this, so this is always a function of the arrow that points to the object of the arrow function definitions
    • Let this function arrow points to the immobilization
    • In addition to this, the following variables are a function of the arrow does not exist, arguments, super, new.target

    Example shows

    var handle = {
        id:'123456',
        init:function(){
            document.addEventListener('click',event => this.doSomeThing(event.type),false)
        },
        doSomeThing:function(type){
            console.log('Handing' + type + 'for' + this.id)
        }
    };
    

    Example Analysis:

    • Use the code above the arrow function init function, which leads to the arrow function inside this, always point to the object handler, otherwise, use this.doSomeThing when called, will error

3. When not to use

  1. Due to this function by the dynamic arrow becomes static, so in the following cases, should not use the arrow functions
    • Define the object's methods
    • Dynamic this time of need

VI. Tail call optimization

1. What is a tail call

  • In the final step is to call a function to another function
function f(x){
    return g(x);
}
  • No return of function calls in accordance with the embodiment, are not the end call
//非尾调用示例
function f(x){
    let y = g(x);
    return y;
}

function f(x){
    return g(x) + 1;
}

function f(x){
    g(x);
}

VII. Trailing comma function parameters

  1. ES2017 allows the last parameter to the function can have a comma after, this is not allowed

to sum up

  1. ES6 may be added as a function of a default value, and the default value may be used with the destructuring assignment
    • The default value is a function of the position of the best on the final surface function parameters, or to use otherwise undefined in the parameter to the default parameters, which makes the default parameters does not make sense
    • Function using a default argument, length returns the number of returns will no default value for the parameter
    • Once the default parameter setting function, to form a single parameter scope
  2. ES6 the rest are new parameters, parameter can accept all the rest parameters are not declared in the function parameter list, you can also substitute the arguments object
  3. Use the default parameter values, destructuring assignment operator and function expansion, internal strict mode can not be specified, otherwise an error
  4. The name attribute function can return the function name, named after the function assigned to the variable, the name property acquired or function of the original name
  5. Arrow function can be simplified writing function, but have noted, this function is always an arrow pointing to the object it is defined outside the city, this dynamic arrow function becomes a fixed

Guess you like

Origin www.cnblogs.com/mapengfei247/p/11105062.html