Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

preface

  • The last article explained the new ES6 syntax. This article is an extension
  • This article explains the use of new functions

The function of new

  • Allows setting default values for function arguments

    let fn = (x, y='vike') = > {
        console.log(x,y)
    }
    
    fn('hello')  // hello vike
    fn('hello'.'world') // hello world
    Copy the code
  • Function parameters are declared by default and cannot be declared again with let,const

    let fn = (x = 1) = > {
        let x = 0 / / an error
        const x = 2 / / an error
    }
    Copy the code
  • Parameter defaults and deconstruction defaults can be used together

    let fn = ({x,y=3}) = > {
        console.log(x,y)
    }
    
    fn({}) // undefined 3
    fn({x:2}) / / 2, 3
    Copy the code
  • The default value of the parameter should be the last parameter of the function. If the parameter is not the last parameter, it cannot be omitted

    let fn = (x=2,y) = > {
        console.log(x,y)
    }
    
    fn() // 2 undefined
    fn(,3) // Error parameters cannot be omitted
    Copy the code
  • Function attributes

    • Length attribute
    • Returns the number of arguments without a default value specified
    let fn = (x) = > {}
    fn.length / / 1
    let fn1 = (x=1) = > {}
    fn1.length / / 0
    Copy the code
    • If the default value is the first parameter, the following parameters are not counted in length
    let fn = (x=1,y) = > {}
    fn.length / / 0
    Copy the code
    • The name attribute
    • Returns the function name of the function
    let fn = () = > {}
    fn.name // 'fn'
    
    (() = >{}).name / /"
    
    (new Function).name // anonymous
    Copy the code
  • scope

    • Once the default values of function parameters are set, the function is initialized to form a local scope
    let fn = (x=1) = > {
        console.log(x)
    }
    
    fn() / / 1
    console.log(x) // x is not defined
    Copy the code
  • Strict mode

    • The extension operator cannot define a strict schema as long as the function uses default destruct assignment values
    // Strict mode
    let fn = () = > {
        'use strict'
    }
    
    // error
    let fn = (x=1) = > {
        'use strict'
    }
    Copy the code
  • Arrow function

    • use= >Define a function
    let f = x= > f
    / / is equivalent to
    let f = (x) = > {
        return f
    }
    Copy the code
    • Use multiple parameters
    let f = (x,y) = > x+y
    / / is equivalent to
    let f = (x,y) = > {
        return x+y
    }
    Copy the code

    conclusion

    • Today’s lesson