Arrow Function in JavaScript

1. Introduction
Arrow Function is a new syntax feature in ES6 (ECMAScript2015).
It is a shorthand form of function expression and is well suited for procedural (as opposed to object-oriented) functional programming.
But it also has many limitations and "disadvantages", such as: no own this object, no arguments parameter, no prototype property, can not be used as a constructor (can not use the new keyword) and so on.
The following will introduce them one by one.


Second, grammar

1, conventional writing
(param1, param2, …, paramN) => { statements } 


2. Abbreviation of parameters
      If there is only one parameter, the parentheses can be omitted.
      If there is no parameter, it cannot be omitted.
// only one parameter
singleParam => { statements }

// no parameters
() => { statements }


3. The abbreviation of the function body
      If there is only one statements expression, the following curly braces can be omitted.
      However, this is equivalent to returning the expression.
// The function body has only one expression
(param1, param2, …, paramN) => expression

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

      However, if the expression is a JSON object, it needs to be enclosed in parentheses.
(param1, param2, …, paramN) => ({name:"John", age:18})


4. Support multiple parameters and set default values ​​for parameters
// Multiple parameters...rest
(param1, param2, ...rest) => { statements }

// parameter default value
(param1 = defaultValue1, param2, …, paramN = defaultValueN) => {
    statements
}


5. Support list structure parameter parsing
var arr = [1, 2];

var f = ([a, b] = arr, {x: c} = {x: a + b}) => a + b + c;

f(); // 6

    Likewise, if the parameter is a JSON object, it needs to be enclosed in parentheses.
// parameter structured parsing
var f = ({length}) => length;

// Parameter structure: {length} is equivalent to {length: ""}



6. Writing format: Do not wrap the line.
    Do not write parameters and arrows in two lines, they need to be written in the same line.
// mistake
var func = ()
           => 1;
// SyntaxError: expected expression, got '=>'



A comprehensive example is shown below:
//
// The following writing will convert materials to [8, 6, 7, 9] and output.

var materials = ['Hydrogen', 'Helium', 'Lithium', 'Beryllium'];

// 1. General
console.log(
    materials.map(function(material) {
      return material.length;
    })
);

// 2. Arrow function
console.log(
    materials.map((material) => {
      return material.length;
    })
);

// 3. Shorthand arrow function
console.log(
    materials.map(material => material.length)
);


// 4. Shorthand + arrow function for parameter structure parsing
console.log(
   //The structure of the parameters passed in is like this: { length: '' }
    materials.map(({length}) => length)
);

//




3. The arrow function does not have its own this object

Before the arrow function appears, the new function object has a this attribute, which points to the object itself.
In arrow functions, however, there is no this object. Therefore, there is no problem that the outer this is overridden or the this itself is overwritten.

1. There is no problem that the outer layer this is rewritten

[Error] Conventional writing method: the outer layer this is replaced by window
function Person() {
    this.age = 0;
    setInterval(function growUp() {
        if(this.age) this.age++;
        console.log(this === window); // true
        console.log(this.age === undefined); // true
    }, 1000);
}

var p = new Person ();

// Because the setInterval method of the window object is called,
// so this points to window
/*
   One more thing, the internal implementation of the setInterval method of window may be like this:
   window.setInterval = function(func, time){
         this.invoke = func;
         //...
   }
   The function parameter passed in the parameter is set as a property of the window object.
   So when calling, the this in the parameter points to the window object.
*/


[Correct] Conventional writing: borrow a that.
function Person() {
    var that = this;
    that.age = 0;

    setInterval(function growUp() {
        that.age++;
        console.log(that.age);
    }, 1000);
}
var p = new Person ();


[Correct] Arrow function: the outer this is successfully passed
function Person(){
    this.age = 0;
    setInterval(() => {
        this.age++;
        console.log(this.age);
    }, 1000);
}

var p = new Person ();



2. There is no problem of this being overwritten.
    When calling the call or apply function, it is impossible to give a this object to the arrow function.
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
    };
    // Passing b as the this object doesn't work.
    return f.call(b, a);
  }
};

console.log(adder.add(1)); // result: 2
console.log(adder.addThruCall(1)); // result: still 2




4. Arrow functions do not have arguments objects 
Arrow functions do not have implicit arguments array objects.
// Example 1:
var arguments = [3, 2, 1];
var arr = () => arguments [0];
arr(); // 3

// Example 2:
function foo(n) {
  // The arguments object here is for the foo function,
  // Not for an f arrow function. Because it doesn't.
  var f = () => arguments [0] + n;
  return f();
}
foo(2); // 4



5. Arrow functions have no prototype attribute 
var Foo = () => {};
console.log(Foo.prototype); // undefined



6. Arrow functions cannot use the new keyword 
var Foo = () => {};
var foo = new Foo(); // TypeError: Foo is not a constructor



Seven, arrow functions cannot use the yield keyword alone The yield keyword 

cannot be used directly in an arrow function (unless it is nested in other functions).
So arrow functions cannot be used directly as Generators .


8. In logical operations, arrow functions need to be enclosed in parentheses
let callback;

callback = callback || function() {}; // ok

callback = callback || (() => {});    // ok

callback = callback || () => {};      
// SyntaxError: invalid arrow-function arguments





Quote:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions







Please indicate the original source :
http://lixh1986.iteye.com/blog/2409009=






Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326313827&siteId=291194637