Did you use ES6 arrow functions correctly?
blog description
The information involved in the article comes from the Internet and personal summary, which is intended to summarize personal learning and experience. If there is any infringement, please contact me to delete it, thank you!
Description
In ES6, it is allowed to use "arrows" ( =>
) to define functions, so many arrow functions appear in our subsequent code writing process, because they are so fragrant! But it also brings some problems, soul torture, do you really understand arrow functions? Because I'm not sure to answer, so this book.
Arrow function
A simple arrow function
// es6
const hello = item => item;
// es5 上面的代码等同于
const hello = function (item) {
return item;
};
Usage (three big ifs)
If the arrow function does not require parameters or requires multiple parameters, use a parenthesis to represent the parameter part.
const hello = () => 'hello';
const sum = (num1, num2) => num1 + num2;
If the code block part of the arrow function is more than one statement, it is necessary to enclose them in curly braces, and use the return
to return.
const sum = (num1, num2) => {
let num = 0;
if(num1 && num2){
num = num1 + num2;
}
return num;
}
If the arrow function returns an object directly, you must add parentheses outside the object, otherwise an error will be reported.
const getInfo = id => ({ id: id, name: "hello" });
Four points of attention
The following four points may have been mentioned countless times and appeared in the major interview questions. Yes, they came again today.
- The arrow function does not have its own
this
object - Can not be used as a constructor, can not use the
new
command - You cannot use the
arguments
object, which does not exist in the function body. If you want to use it, you can use the rest parameter instead - The
yield
command cannot be used, so arrow functions cannot be used as generator functions
The this point of the arrow function
For ordinary functions, the internal this
points to the object where the function is running. Arrow function does not own this
objects inside the this
when the top is the definition of scope of this
.
this
direction inside the arrow function is fixed. In contrast, the this
direction of the ordinary function is variable.
Convert ES6 to ES5
I found that this, which is actually just the so-called arrow function, was only "borrowed" from outside
// ES6
function foo() {
setTimeout(() => {
console.log('id:', this.id);
}, 100);
}
// ES5
function foo() {
var _this = this;
setTimeout(function () {
console.log('id:', _this.id);
}, 100);
}
In setInterval, there is actually no this.s2, so its value will not change.
function test() {
this.s1 = 0;
this.s2 = 0;
// 箭头函数
setInterval(() => this.s1++, 1000);
// 普通函数
setInterval(function () {
this.s2++;
}, 1000);
}
s1 // 1
s2 // 0
S2 can be modified after ordinary function modification
// 普通函数
setInterval(function () {
let _this = this;
_this.s2++;
}, 1000);
Here you can also see the direction of this of the arrow function, and you can find that the arrow function is very suitable for callbacks.
Cannot be used as a constructor
Cannot be used as a constructor, this is easy to understand. Because the arrow function does not have its own this
, how can it be constructed? Therefore, arrow functions cannot be used as constructors. The new keyword cannot be used either.
Cannot use arguments object
Like this, arguments
points to the corresponding variable of the outer function, and similar brothers also have super
, new.target
function hello() {
setTimeout(() => {
console.log('args:', arguments);
}, 1000);
}
hello(1,2,3,4)
// args: [1, 2, 3, 4]
Because of this problem, the arrow function cannot use call()
, apply()
, bind()
these methods to change this
, so the this of the arrow function is "static".
The good and bad of arrow functions
Speaking of the this of the arrow function, there is no such this
. In fact, it is not the case. The 060f6b3c231826 object before ES6 has always been a headache. When using it carefully, the code will be blurred when there are more callbacks. It is precisely because of the emergence of this "static" this that these problems have been improved.
When using arrow functions, you should make reasonable use of the advantages and disadvantages of arrow functions and choose the right scene. Don't use arrow functions when defining object methods and dynamically binding this.
thanks
Universal network
Ruan Yifeng's ES6 Tutorial
And hardworking self, personal blog , GitHub
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。