This is the 17th day of my participation in the August Text Challenge.More challenges in August

Arrow function

Arrow function expressions have a much cleaner syntax than function expressions and don’t have their own this, arguments, super, or new.target. The arrow function expression is more useful where anonymous functions are needed, and it cannot be used as a constructor.

case

const materials = ['Hydrogen'.'Helium'.'Lithium'.'Beryllium']
console.log(materials.map((material) = > material.length))
// expected output: Array [8, 6, 7, 9]
Copy the code

Basic grammar

(param1, param2,... , paramN) => {statements} (param1, param2,... , paramN) => expression// Equivalent to: param1, param2... , paramN) =>{ return expression; }

// Parentheses are optional when there is only one argument:
(singleParam) => { statements }
singleParam => { statements }

// Functions with no arguments should be written in parentheses.
() => { statements }
Copy the code

Advanced grammar

// The bracketed function body returns an object literal expression:
params => ({foo: bar})

// Support remaining parameters and default parameters(param1, param2, ... Rest) => {statements} (param1 = defaultValue1, param2,... , paramN = defaultValueN) => { statements }Argument list deconstruction is also supported
let f = ([a, b] = [1.2], {x: c} = {x: a + b}) = > a + b + c;
f();  / / 6
Copy the code
The introduction of arrow functions has two main uses: shorter functions and no this binding

The arrow function does not create its own this; it only inherits this from the upper level of its scope chain. Therefore, in the following code, the value of this in the function passed to setInterval is the same as that in the enclosing function:

function Person() {
  this.age = 0

  setInterval(() = > {
    this.age++ / / | this | to p instance correctly
  }, 1000)}var p = new Person()
Copy the code

throughcallandapplycall

Since arrow functions do not have their own this pointer, when a function is called through call() or apply(), only arguments (not this) are passed, and their first argument is ignored.

var adder = {
  base : 1,

  add : function(a) {
    var f = v => v + this.base;
    return f(a);
  },

  addThruCall: function(a) {
    var f = v => v + this.base;
    var b = {
      base : 2
    };

    returnf.call(b, a); }}; console.log(adder.add(1));         2 / / output
console.log(adder.addThruCall(1)); // Still output 2
Copy the code
Use arrow functions as methods

When the arrow function is used as a method, the method points to the scope of the previous chain in the method because the this binding is not defined. The following example points to the global scope.

// Use the arrow function as a method
var obj = {
  a: 1.b: () = > {
    console.log(this.a, this)},c: function () {
    console.log(this.a, this)}},//obj.b() //undefined {}
// This is run in node environment, run in browser environment: undefined,window
//obj.c() //1 {a:1.b:[Function:b],c:[Function:c]}
Object.defineProperty(obj, 'b', {
  get: () = > {
    console.log(this.a, typeof this.a, this)
    return this.a++
  },
})
//obj.b //undefined 'undefined' {}
// The arrow function cannot be used as a constructor. Using it with new will cause an error
/*(var Foo = () => {}
var f = new Foo()*/
// The arrow function has no prototype attribute
// Arrow functions cannot be used as function generators.
Copy the code
A few more caveats:
  • The arrow function returns a subdimension object in parentheses (this is because the code inside curly braces ({}) is parsed as a series of statements (that is, foo is treated as a label, not part of the object literal).
  • The scope of the arrow function is local
//
var greeting = () = > {
  let now = new Date(a)return 'Good' + (now.getHours() > 17 ? ' evening.' : ' day.')
}
greeting() //"Good day."
console.log(now) // ReferenceError: Now is not defined in the let scope of the standard

// Variables defined in parentheses are local variables (default arguments)
var greeting = (now = new Date(a)) = >
  'Good' + (now.getHours() > 17 ? ' evening.' : ' day.')
greeting() //"Good day."
console.log(now) // ReferenceError: now is not defined

{}} are global variables that do not use var
var greeting = () = > {
  now = new Date(a)return 'Good' + (now.getHours() > 17 ? ' evening.' : ' day.')
}
greeting() //"Good day."
console.log(now) // Fri Dec 22 2017 10:01:00 GMT+0800

// Contrast: the variables defined by var in {} are local variables
var greeting = () = > {
  var now = new Date(a)return 'Good' + (now.getHours() > 17 ? ' evening.' : ' day.')
}
greeting() //"Good day."
console.log(now) // ReferenceError: now is not defined
Copy the code

Above is an example of MDN.

  • The same arrow function can also use closures and recursion
The difference between arrow functions and anonymous functions
  • This points to difference

    • Arrow functions bind the parent context based on the context in which this refers. Bind this to lexical scope
    • This refers to the window in the anonymous function
A few points to note when using the arrow function
  • 1. The this object inside the function is the object at which it is defined, not used.

  • 2. It cannot be used as a constructor, i.e., it cannot instantiate an object with the new command, otherwise an error will be thrown.

  • You can never use the arguments object. This object does not exist in the function body.

  • 4. Do not use yield and arrow functions as Generator functions.