arrow function
The arrow function is a new representation of functions in es6. It takes the simplicity of functions to the extreme! Let's look at the simplest arrow function first:
let fn = a => a
var m = prompt()
alert(fn(m))
1. Arrow function writing
1. If there is only one statement, {} and return can be omitted
let fn = a => a+a
//相当于
let fn = function(a){
return a+a;
}
2. If there are multiple statements, {} and return cannot be omitted
let fn = a => {
var b = 0;
console.log(a,b);
}
fn(10)
There are two more points to note!
one,
- When passing a single parameter, there is no need to add parentheses ()
var fn = a => a
- Parentheses are required when passing multiple values
var fn = (a,b)=>a+b
two,
When omitting {} and return, if the returned content is an object, the object needs to be enclosed in brackets ()
Without parentheses, it will be undefined
var fn = a=>({ a:'你好'}) console.log(fn())
2. Arrow functions cannot be used in constructors
First look at the constructor
var ful=function(age){
this.age=age;
}
var chl=new ful(18);
console.log(chl.age);//18
After changing to arrow function
var ful = age => {
this.age=age;
}
var chl=new ful(18);//ful is not a constructor
console.log(chl.age);
3. Arrow function has no prototype property
var fn = () => {
};
console.log(fn.prototype); // undefined
4. Arrow function does not bind this
There is no pointer to this in the arrow function, and the pointer to this in the arrow function will point to the scope closest to him
Here's an interview question:
window.color = "red";
//let 声明的全局变量不具有全局属性,即不能用window.访问
let color = "green";
let obj = {
color: "blue",
getColor: () => {
return this.color;//this指向window
}
};
let sayColor = () => {
return this.color;//this指向window
};
console.log(obj.getColor())
obj.getColor();//red
console.log(sayColor())
sayColor();//red
Summarize
- There is no pointer to this in the arrow function, and the pointer to this in the arrow function will point to the scope closest to him
- Arrow functions cannot be used as constructors
- There is no arguments argument in the arrow function