Arrow function:
definition:
通俗的理解 箭头函数就是return函数
Definition:
ES6 allows the use of "arrows" (=>) to define functions
Basic format:
() => {
}
eg:
let xx = ()=> 555
console.log( xx() )
就等同于:
function xx2() {
return 666;
}
console.log( xx2())
The syntax of an arrow function:
- () to define parameters, if there is only one parameter, you don’t need to write parentheses (if there are many parameters, you can use "," to separate them in parentheses);
- Write the function body in {}, if there is only a return value in the function body, you don’t need to write return;
The difference between arrow functions and ordinary functions:
For example:
it is obviously possible to output
and then improve it:
let obj = {
name = "小明",
age = 2,
sayName(){
//console(`我是${this.name}`)
setTimeout(function(){
console.log("我是" + this.name)
},500)
}
}
obj.sayName();
Do you think "I am Xiao Ming" will be output after 0.5s this time?
Like it if you think it's okay,
forward it if you don't think it's okay
Let's look at the effect:
obviously there is no output
Then we:
where this refers to the window object, and the window object is the global object
This is a method within a method.
The this in the external method refers to Xiaoming.
The output of the method inside is the window object.
If it is es5,
we can use this method (pass value) to get Xiaoming's name
If you use an arrow function, you can use this:
So why can you use arrow functions when you can use ordinary functions?
The difference between the arrow function and the ordinary function is obtained:
- This points to different:
ordinary functions, whoever calls this this points to who
Arrow function, where the function is defined, this points to who
(it can be understood that the internal arrow function will not change the object this points to, this still points to the scope of the outer function )