current position:Home>Today, let's talk about the arrow function of ES6
Today, let's talk about the arrow function of ES6
2021-08-26 19:59:19 【edison】
This is my participation 8 The fourth of the yuegengwen challenge 17 God , Check out the activity details :8 Yuegengwen challenge
Arrow function
The syntax of arrow function expression is more concise than function expression , And there's no one of its own this
,arguments
,super
or new.target
. Arrow function expressions are more suitable for places where anonymous functions are needed , And it cannot be used as a constructor .
example
const materials = ['Hydrogen', 'Helium', 'Lithium', 'Beryllium']
console.log(materials.map((material) => material.length))
// expected output: Array [8, 6, 7, 9]
Copy code
Basic grammar
(param1, param2, …, paramN) => { statements }
(param1, param2, …, paramN) => expression
// amount to :(param1, param2, …, paramN) =>{ return expression; }
// When there is only one parameter , Parentheses are optional :
(singleParam) => { statements }
singleParam => { statements }
// Functions without arguments should be written as a pair of parentheses .
() => { statements }
Copy code
Advanced Grammar
// The bracketed function body returns the object literal expression :
params => ({foo: bar})
// The remaining parameters and default parameters are supported
(param1, param2, ...rest) => { statements }
(param1 = defaultValue1, param2, …, paramN = defaultValueN) => {
statements }
// Parameter list deconstruction is also supported
let f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c;
f(); // 6
Copy code
The introduction of arrow function has two main functions : Shorter functions and no binding this
Arrow functions do not create their own this
, It will only inherit from the upper level of its scope chain this
. therefore , In the following code , Pass to setInterval
Within the function of this And... In closed functions this
Same value :
function Person() {
this.age = 0
setInterval(() => {
this.age++ // |this| Point to... Correctly p example
}, 1000)
}
var p = new Person()
Copy code
adopt call
and apply
call
because Arrow function does not have its own this The pointer , adopt call() or apply() Method to call a function , Only parameters can be passed ( Can't bind this), Their first parameter will be 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
};
return f.call(b, a);
}
};
console.log(adder.add(1)); // Output 2
console.log(adder.addThruCall(1)); // Still output 2
Copy code
Use the arrow function as the method
When the arrow function is used as a method , Because there is no definition this
binding , Method points to the scope of the previous scope chain . The following example points to the global scope .
// Use the arrow function as the method
var obj = {
a: 1,
b: () => {
console.log(this.a, this)
},
c: function () {
console.log(this.a, this)
},
}
//obj.b() //undefined {}
// It's on it node Operating in the environment , Running in a browser environment will output :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' {}
// Arrow functions cannot be used as constructors , and new Using it together will report an error
/*(var Foo = () => {} var f = new Foo()*/
// There's no arrow function prototype attribute , The same mistake
// Arrow functions cannot be used as function generators .
Copy code
There are a few more points to note :
- When the arrow function returns the sub surface quantity object, parentheses should be added ( It's because of curly braces ({} ) The code inside is parsed into a series of statements ( namely foo It's considered a label , Instead of being part of the object literal ).)
- Note the scope of the arrow function , Is local scope
// Conventional writing
var greeting = () => {
let now = new Date()
return 'Good' + (now.getHours() > 17 ? ' evening.' : ' day.')
}
greeting() //"Good day."
console.log(now) // ReferenceError: now is not defined The standard let Scope
// The variables defined in parameter brackets are local variables ( Default parameters )
var greeting = (now = new Date()) =>
'Good' + (now.getHours() > 17 ? ' evening.' : ' day.')
greeting() //"Good day."
console.log(now) // ReferenceError: now is not defined
// contrast : Function body {} Don't use var The defined variable is a global variable
var greeting = () => {
now = new Date()
return 'Good' + (now.getHours() > 17 ? ' evening.' : ' day.')
}
greeting() //"Good day."
console.log(now) // Fri Dec 22 2017 10:01:00 GMT+0800 ( China standard time )
// contrast : Function body {} use var The variables defined are local variables
var greeting = () => {
var now = new Date()
return 'Good' + (now.getHours() > 17 ? ' evening.' : ' day.')
}
greeting() //"Good day."
console.log(now) // ReferenceError: now is not defined
Copy code
It's on it MDN Example .
- The same arrow function can also use closures and recursion
The difference between arrow function and anonymous function
-
this Pointing difference
- The arrow function depends on the environment ( In which environment do I ,this Just point to who ),Arrow functions bind the parent context. Bind by lexical scope this
- In anonymous functions this Point to window
Using the arrow function, pay attention to several points
-
1、 In function body this Object is the object of definition , Instead of using the object ;
-
2、 Cannot be used as a constructor , That is to say, it can't be used new Command to instantiate an object , Otherwise, an error will be thrown ;
-
3、 Not available arguments object , The object does not exist inside the function , If you want to use it , It can be used rest Parameters instead of ;
-
4、 Not available yield command , Arrow functions cannot be used as Generator function ;
copyright notice
author[edison],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210826195917282W.html
The sidebar is recommended
- Crazy blessing! Tencent boss's "million JVM learning notes", real topic of Huawei Java interview 2020-2021
- JS JavaScript how to get the subscript of a value in the array
- One line of code teaches you how to advertise on Tanabata Valentine's Day - Animation 3D photo album (music + text) HTML + CSS + JavaScript
- BEM - a front-end CSS naming methodology
- Another ruthless character fell by 40000, which was "more beautiful" than Passat and maiteng, and didn't lose BMW
- August 23, 2021 Daily: less than three years after its establishment, Google dissolved the health department
- CSS learning notes - Flex layout (Ruan Yifeng tutorial summary)
- Zheng Shuang's 30th birthday is deserted. Chen Jia has been sending blessings for ten years. Is it really just forgetting to make friends?
- Asynchronous solution async await
- "The story of huiyeji" -- people are always greedy, and fairies should be spotless!
guess what you like
-
Installing Vue devtool for chrome and Firefox
-
Basic usage of JS object
-
1. JavaScript variable promotion mechanism
-
Front end Engineering - scaffold
-
Mediator pattern of JavaScript Design Pattern
-
Array de duplication problem solution - Nan recognition problem
-
New choice for app development: building mobile applications using Vue native
-
Vieira officially terminated his contract and left the team. The national security club sent blessings to him
-
Less than 200000 to buy a Ford RV? 2.0T gasoline / diesel power, horizontal bed / longitudinal bed layout can be selected
-
We are fearless in epidemic prevention and control -- pay tribute to the front-line workers of epidemic prevention!