What is arrow function?
Arrow functions do the same thing as normal functions in a more concise way, but do not have the same properties as normal functions: this, arguments, super, new.target
1.(... args) => expression
Args indicates that there are 0, 1, and multiple parameters. Expression Indicates a JS expression with only one line of code.
2,(... args) => { body }
Args indicates that there are 0, 1, and multiple parameters. Body indicates multiple lines of code, the last line of which must be a return statement.
Two, different expressions:
1. Different parameters, different writing methods
// 1. No parameters
let test = () = > alert("Hello!");
// 2, only one argument :() can be omitted
let test = n= > n * 2;
let test = (n) = > n * 2;
// equivalent to the following ordinary function
let test = function (n) {
return expression;
};
Copy the code
2, different expressions, different writing methods
Return ({});
let func = (arg1, arg2, ... argN) = > {
return expression;
}
// equivalent to the arrow function below
let func = (arg1, arg2, ... argN) = > expression
// equivalent to the following ordinary function.
let func = function (arg1, arg2, ... argN) {
return expression;
};
Copy the code
3. For conditional operators
let age = prompt("What is your age?".18);
let welcome = (age < 18)?() = > alert('Hello') :
() = > alert("Greetings!");
welcome();
Copy the code
4. Array traversal
var elements = [
'Hydrogen'.'Helium'.'Lithium'.'Beryllium'
];
// 1.
elements.map(function (element) {
return element.length;
});
// 2, arrow function:
elements.map((element) = > {
return element.length;
});
// 3, only one parameter, can be omitted ()
elements.map(element= > {
return element.length;
});
Return ({});
elements.map(element= > element.length);
// 5
// Each element in the elements array has a length attribute, which can be destructed as follows:
// Note: lengthFooBArX is only a variable and can be replaced with any legal variable name
elements.map(({ "length": lengthFooBArX }) = > lengthFooBArX);
[8, 6, 7, 9]
Copy the code
5. For recursion
var fact = (x) = > (x == 0 ? 1 : x * fact(x - 1));
fact(5);
// Output: 120
Copy the code
6. Use closures
(I =0 is the default argument)
var Add = (i = 0) = > {
return (() = > (++i))
};
var v = Add();
v(); / / 1
v(); / / 2
// Since there is only one return, the return and parentheses () can also be omitted
var Add = (i = 0) = > () = > (++i);
Copy the code
7. Examples of other forms
// 1, empty arrow function returns undefined
let empty = () = >{};// return "foobar"
(() = > 'foobar') ();// 3. More concise Promise chains
promise.then(a= > {
// ...
}).then(b= > {
// ...
});
// Arrow functions without arguments are visually easy to analyze
setTimeout(() = > {
console.log('I happen sooner');
setTimeout(() = > {
// deeper code
console.log('I happen later');
}, 1);
}, 1);
Copy the code
Three, important features
No arguments
// arguments are used correctly in normal functions:
function foo(n) {
// Implicitly bind the arguments to function foo with the arguments object.
// arguments[0] denotes the first argument passed to foo (n)
var f = () = > arguments[0] + n;
return f();
}
foo(1); / / 2
foo(3); / / 6
foo(3.2);/ / 6
// arguments cannot be used in arrow functions
// ReferenceError: arguments is not defined
var func = (a, b) = > {
return arguments[0];
}
Copy the code
2. No Prototype attribute
var Foo = () = > {};
console.log(Foo.prototype); // undefined
Copy the code
3. You can’t use new
Arrow functions without this cannot be used as constructors and therefore cannot use new
var Foo = () = > {};
var foo = new Foo(); // TypeError: Foo is not a constructor
Copy the code
Four, need () scene
1. Objects as expressions
Use () to wrap the object represented by {} as an expression, otherwise {} will be parsed as an expression, resulting in syntax errors.
// Calling func() returns undefined!
var func = () = > { foo: 1 };
// SyntaxError: function statement requires a name
var func = () = > { foo: function() {}};// The correct way to write this is:
var func = () = > ({ foo: 1 });
var func = () = > ({ foo: function () {}});Copy the code
2, line breaks,
SyntaxError: Expected expression, got '=>'
var func = () = > 1;
// 2, correct, can be after => line break
var func = (a, b, c) = >
1;
// 3, correct, use () to break a line
var func = (a, b, c) = > (
1
);
// 4, correct, use () to break a line
var func = (a, b, c) = > 1;
Copy the code
3. As a separate expression
let callback;
// 1
callback = callback || function () {};// 2, error: invalid arrow-function arguments
callback = callback || () = >{};// 3
callback = callback || (() = >{});// ok
Copy the code
Arrow functions do not have this
This in ordinary functions, object methods, is defined at run time.
- Normal function this equals undefined and cannot be called;
- This of the object method refers to the object itself.
- The arrow function does not define its own this, it only inherits its this from the previous scope.
1. Arrow functions in the object
var obj = {
i: 10.b: () = > console.log(this.i, this),
c: function () {
console.log(this.i, this)
}
}
obj.b();
// Undefined, Window{... }
Arrow function b, which has no upper scope to inherit this, is not accessible.
obj.c();
// Output result: 10, Object {... }
Copy the code
2. Use this correctly in the arrow function
// Example 1:
function Person() {
this.age = 0;
// The arrow function inherits this as an argument to setInterval
setInterval(() = > {
this.age++;
console.log("age:".this.age);
}, 1000);
}
var p = new Person();
Copy the code
// Example 2:
The arrow function student inherits showList's this
let group = {
title: "Our Group".students: ["John"."Pete"."Alice"].showList() {
this.students.forEach(
student= > alert(this.title + ':'+ student) ); }}; group.showList();Copy the code
3. Ordinary functions cannot access this
# in ordinary functionsthisIs equal to theundefinedUsed,this.title must be an error because it cannot be recognizedlet group = {
title: "Our Group".students: ["John"."Pete"."Alice"].showList() {
this.students.forEach(function (student) {
// Error: Cannot read property 'title' of undefined
alert(this.title + ':'+ student) }); }}; group.showList();Copy the code
Six, reference links:
- Is arrow function in JavaScript different from normal function?