Extension of function


Extension of function

  • Default values for function parameters

    //The old method adds default values inside the function
    function foo(value){
    //Value = value | true // true is the default value. If false is passed in, the default value will also be used. Obviously, there is an error
    value = value === undefined?true:value
    //Add default values to parameters
    Function bar (value = true) {// when there are multiple parameters, the default value should be placed last
  • The length attribute of the function

When a default value is specified, the length attribute is distorted and the rest parameter is not included in the length attribute

(function (a) {}).length // 1
(function (a = 5) {}).length // 0
(function (a, b, c = 5) {}).length // 2
(function(...args) {}).length // 0
  • Scope of function

When the function is declared and initialized, the parameters form a separate scope (context). After initialization, the scope will disappear. This syntax behavior will not appear when the parameter default value is not set

var x = 1;
function f(x, y = x) {
f(2) // 2

In the above code, the default value of parameter Y is equal to variable x. When function f is called, the parameters form a separate scope. In this scope, the default value variable x points to the first parameter x instead of the global variable x, so the output is 2

let x = 1;
function f(y = x) {
  let x = 2;
f() // 1

In the above code, when function f is called, the parameter Y = x forms a separate scope. In this scope, the variable x itself is not defined, so it points to the outer global variable x. When a function is called, the local variable x inside the function body does not affect the default value variable x. If the global variable X does not exist at this time, an error will be reported.

  • Remaining parameters rest
function foo()
  console.log(arguments,Array.from(arguments)); // Pseudo arrays are arrays
Function bar (... Args) {// the last bit of the formal parameter can only be used once
  • Name attribute
    The name property of the function returns the function name of the function

    function foo() {}
    foo.name // "foo"
  • Arrow function

    • Arrow functions are anonymous functions. Ordinary functions can be named or anonymous
    • The arrow function itself does not have this. When declaring, it can capture this in its context for its own use (this will not change once it is captured). The ordinary function points to window
    • The arrow function, combined with call and apply, cannot change its direction, and always points to the context (call, apply, bind)
    • Arrow function cannot be treated as constructor new
    • The arrow function has no prototype object, prototype
    • The arrow function cannot use the arguments object. If you want to use it, you can use the rest parameter instead
    • You cannot use the yield command, so the arrow function cannot be used as a generator function