Arrow function expressions have a cleaner syntax than function expressions and do not have their own this. The arrow function expression is more useful where anonymous functions are needed, and it cannot be used as a constructor.

Basic grammar:

The usual way to define a function is:

var fn1 = function(a, b) {
    return a + b
}

function fn2(a, b) {
    return a + b
}
Copy the code

Use the ES6 arrow function syntax to define a function, removing the function keyword and function name from the original function, and using => to concatenate the argument list with the function body.

var fn1 = (a, b) = > {
    return a + b
}

(a, b) => {
    return a + b
}
Copy the code

When a function has only one argument, the parentheses can be omitted. However, parentheses cannot be omitted when there are no arguments.

/ / no arguments
var fn1 = function() {}
var fn1 = () = > {}

// Single parameter
var fn2 = function(a) {}
var fn2 = a= > {}

// Multiple parameters
var fn3 = function(a, b) {}
var fn3 = (a, b) = > {}

// variable parameters
var fn4 = function(a, b, ... args) {}
var fn4 = (a, b, ... args) = > {}
Copy the code

Arrow functions are equivalent to anonymous functions and simplify function definitions.

Arrow functions have two formats:

  • Contains only one expression, omitting {… } and return.
  • It can contain more than one statement and cannot omit {… } and return
() = >return 'hello'

(a, b) => a + b
(a) => {
    a = a + 1
    return a
}
Copy the code

If you return an object, be careful. If you return a custom object with a single expression, you will get an error without parentheses, because {… } there are syntax conflicts.

Note that enclosing braces in curly braces is the definition of the object, not the body of the function

x => {key: x} / / an error
x => ({key: x}) / / right
Copy the code

Basic features of arrow functions

  • The arrow function this is this in the parent scope, not this when called

The arrow function’s this always points to its parent scope and cannot be changed by any method, including call, apply, or bind.

  • Arrow functions cannot be constructors; new cannot be used

  • Arrow functions have no arguments, caller, callee

The arrow function itself has no arguments. If the arrow function is inside a function, it will take arguments from the external function and use them.

  • The arrow function is called through call and apply and does not change the this pointer, but only the arguments
let obj2 = {
    a: 10.b: function(n) {
        let f = (n) = > n + this.a;
        return f(n);
    },
    c: function(n) {
        let f = (n) = > n + this.a;
        let m = {
            a: 20
        };
        returnf.call(m,n); }};console.log(obj2.b(1));  / / 11
console.log(obj2.c(1)); / / 11
Copy the code
  • Arrow functions cannot be Generator functions and cannot use the yield keyword

  • Arrow functions have no stereotype attributes

var a = () = >{
  return 1;
}

function b(){
  return 2;
}

console.log(a.prototype);  // undefined
console.log(b.prototype);   / / {constructor: ƒ}
Copy the code
  • The multiple arrow function is a higher-order function, equivalent to an inline function
const add = x= > y= > y + x;
/ / equivalent to
function add(x){
  return function(y){
    return y + x;
  };
}
Copy the code

Matters needing attention

Syntax for argument lists and return values

  • For 1 parameter, write the parameter name on the left side. For 0 or more parameters, enclose the parameter list with ()

  • If the function body has only one statement, the value on the right side automatically becomes the return value of the function. If the function body has more than one statement, the function body needs to be wrapped with {} and a manual return is required

An ambiguous character

{is the only ambiguous character, so return object literals wrapped in (), otherwise they will be treated as block statements:

var f1 = () = > {};
f1();   / / returns undefined
/ / equivalent to the
// var f1 = function() {};

var f2 = () = > ({});
f2();   // Return an empty object {}
/ / equivalent to the
// var f2 = function() {return {}; };
Copy the code

About this

Arrow functions inherit this from the enclosing scope. To avoid that = this, observe that arrow functions are used for all functions except for direct function attribute values on objects.

/ / scenario 1
function MyType() {}
MyType.prototype.fn = function() {/* Define the arrow function */};  // The arrow function this points to an instance of type MyType

/ / scenario 2
var obj = {};
obj.fn = function() {/* Define the arrow function */};   // Arrow function this points to obj
Copy the code

Function can define a new this, but arrow function cannot. It can only borrow this from the outer layer. So, use function when you need a new this, and use the arrow function when you want the outer this

About Arguments objects

Arrow functions don’t have arguments objects, because the standard encourages default argument, variadic argument deconstruction

// General function
(function(a) {console.log(`a = ${a}, arguments[0] = The ${arguments[0]}`)}) (1);
// log print: a = 1, arguments[0] = 1

// The arrow function equivalent to the above
(a= > console.log(`a = ${a}, arguments[0] = The ${arguments[0]}`(a))1);
// log print: Uncaught ReferenceError: arguments is not defined
Copy the code