Extension of a function

  • Default values for function parameters

    / / the old way by adding the default function within the function foo (value) {/ / value = value | | true / / true as the default value, if the incoming false then will use the default, So obviously value = value === undefined, right? true:value console.log(value); } foo(false) function bar(value=true){// For multiple arguments, the default value is last}
  • The length attribute of the function

When a default value is specified, the Length attribute is distorted and the REST parameters do not count toward the Length attribute

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

When a function is declared and initialized, the arguments form a separate context. When initialization is complete, the scope will disappear. This syntactic behavior does not occur without setting the default value of the parameter

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

In the above code, the default value of the parameter y is equal to the variable x. When the function f is called, the arguments form a separate scope. In this scope, the default variable x refers to the first parameter x, not 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 the function f is called, the parameter y = x forms a separate scope. In this scope, the variable x itself is not defined, so it refers to the outer global variable x. When a function is called, the local variable x inside the function body does not affect the default variable x. If the global variable x does not exist at this point, an error will be reported.

  • Remaining parameter REST
function foo() { console.log(arguments,Array.from(arguments)); } foo(1,2,3,4)
function bar(... Args){// The last bit of the parameter can only be used once, console.log(args); } bar (1, 2, 3, 4)
  • The name attribute of a function, which returns the name of the function

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

    • Arrow functions are anonymous. Normal functions can be named or anonymous
    • The arrow function itself does not have this. It can capture the context in which this is declared for its own use (once this is captured, it does not change). Normal functions point to window
    • Arrow functions combined with call and apply do not change the point, always refer to the context (call, apply, bind)
    • The arrow function cannot be treated as the constructor new
    • Arrow functions have no prototype object, prototype
    • Arrow functions cannot use arguments objects; if they do, rest arguments can be used instead
    • You cannot use yield, so arrow functions cannot be used as Generator functions