Arrow function features: simplified code writing
- Arrow functions do not have the “function” keyword
- Parentheses and braces are preceded by arrows “=>”
- You can omit the parentheses if the parameter has only one
- You can omit the braces if there is no return
- If the return value is an object, enclose the return value in parentheses
// The old way of writing
var fn = function(a){
return a;
}
console.log(fn(1));
/ / 1
Copy the code
/ / ES6 writing
let fn = a= >a;
console.log(fn(1));
/ / 1
Copy the code
// A function is nested within another function
// The old way of writing
function a(c){
function b(d){
returna+b; }}/ / ES6 writing
let a = c= >d= >c+d;
console.log(a(2) (3));
/ / 5
Copy the code
// A function nested within another function returns an object
// The old way of writing
function a(c){
function b(d){
return {sum:a+b}; }}/ / ES6 writing
let a = c= >d= >({sum:c+d});
console.log(a(2) (3));
// { sum: 5 }
Copy the code
Arrow function features: This points to
This points to the problem resolution
- The scope before calling this is resolved by let that = this
- Bind the current scope to this of the previous scope (call apply can also be used if asynchrony is not available)
- Arrow function
let obj = {
a:1.b:function(){
let that = this
setTimeout(function(){
console.log(that) //window
},1000)
}
}
obj.b();
Copy the code
let obj = {
a:1.b:function(){
setTimeout(function(){
console.log(this) //window
}.bind(this),1000)
}.bind(this)
}
obj.b();
Copy the code
let obj = {
a:1.b:() = >{
setTimeout(() = >{
console.log(this) //window
},1000)
}
}
obj.b();
Copy the code
- There is no this in the arrow function, so each time this is evaluated, the arrow function is searched in the upper scope. If there is no this in the upper scope, the arrow function is searched in the upper scope
let obj = {
a:1.b:() = >{
setTimeout(() = >{
console.log(this); //window
},100)
}
}
obj.b();
Copy the code
example
- Object braces are not considered a scope
- Variables declared by the let are not mounted to the window
let a =1;
let obj = {
a:2.b:() = >{
console.log(this); //window
console.log(this.a); // undefined
console.log(a); / / 1
}
}
obj.b();
Copy the code
var a =1;
let obj = {
a:2.b:() = >{
console.log(this); //window
console.log(this.a); / / 1
console.log(a); / / 1
}
}
obj.b();
Copy the code
Arrow function multi-argument passing (residual operator)
- Arrow functions have no arguments
- . The rest of the operator can put the last parameter in an array.
let fn = (a,... arr) = >{
console.log(arr)
}
fn('sssss'.1.3.2.33.22.345)
// [1, 3, 2.33, 22, 345]
Copy the code
Personal blog cometang:www.gotang.cn