Arrow function
preface
Note: arrow functions differ from normal functions only when this points to different points.
The difference between the arrow function
- Syntax is more concise and intuitive.
- Inherits from above the scope
this
. Bind, call and apply
Has no effect on arrow functions.- Is not binding
arguments
Object. - You can’t use
new
The keyword. - There is no prototype
(prototype)
.
1. Simpler syntax
(param1, param2,... , paramN) => {returnStatements} (param1, param2... , paramN) => statements// Parentheses are optional when there is only one argument
(param1) => statements
// If the statements returned are objects, they need to be enclosed in parentheses
param1 => (statements)
// a pair of parentheses when there are no arguments
() => { statements }
Copy the code
2. Inherit this from the upper level of the scope.
// Convert ES6 to ES5 using bable
// ES6
const obj = {
getArrow() {
return () = > {
console.log(this=== obj); }; }}// ES5 after conversion
var obj = {
getArrow: function getArrow() {
var _this = this;
return function () {
console.log(_this === obj); }; }};Copy the code
From the transformed code, we can see that the arrow function this is retrieved when defined, not when called.
3. Bind, call, and apply have no effect on arrow functions
As you can see from the transformed arrow function code, there is no “this” in the execution function. Instead, the variables are retrieved directly, so calling the arrow function call, apply, and bind will not work.
4. No bindingarguments
Object.
Arrow functions have no arguments objects of their own
/ / the first
let f = (v) = > {
console.log(v)
console.log(arguments)
}
f(123) // arguments are not defined
/ / the second
let f = function (v) {
console.log(arguments) / / [123]
return () = > {
// Inherits arguments from the upper scope
console.log(arguments) / / [123]
}
}
f(123) ()/ / is not an error
Copy the code
An error is reported if the upper scope is global, otherwise arguments from the upper scope are inherited.
5. Do not use the new keyword
Arrow functions cannot be used as constructors; using them with new throws an error.
var Foo = () => {};
var foo = new Foo(); // TypeError: Foo is not a constructor
Copy the code
6. No prototype
Arrow functions have no prototype attribute.
var Foo = () => {};
console.log(Foo.prototype); // undefined
Copy the code
To recap:
- Arrow functions have a cleaner syntax,
- The arrow function’s this is the inherited upper scope.
- Arrow functions do not have their own Argumnets.
- Arrow functions that use call, bind, and apply do not change the this pointer. They simply pass arguments.
- Arrow functions cannot use the new keyword.
- Arrow functions have no prototype attribute.
See here you have no doubt?? Why not use the new keyword
Argumnets and Prototype are not found in the arrow function, and call has no effect on the arrow function. Natural new is not good, are chain reaction….. .
Reference: MDN arrow function