什么是Arrow Function Expression:
An arrow function expression is a compact alternative to a traditional function expression, with some semantic differences and deliberate limitations in usage:
箭头函数表达式是传统函数表达式的紧凑替代品,有些语义上的限制
-
Arrow functions don't have their own bindings to this, arguments, or super, and should not be used as methods.
-
箭头函数对this,参数,super没有绑定,不应该做为方法使用
-
-
Arrow functions cannot be used as constructors. Calling them with new throws a TypeError. They also don't have access to the new.target keyword.
-
不能用做构造汗水,会报错。
-
-
Arrow functions cannot use yield within their body and cannot be created as generator functions.
-
不能作为生成器函数,不能在构造函数主体内使用yield
-
Syntax:
我这里“抄袭了一下文档并且结合了下前辈的经验”
//Traditional function
const multiply = function ()
{
return num * num;
}
//Arrow function
const multiply => num * num;
//with param
//Traditional function
const multiply = function (num1, num2)
{
return num1 * num2
}
//Arrow function
const multiply = (num1, num2)=> num1 * num2;
const add10 = (num) => num + 10
2. (param) => expression
//Traditional function
const multiply = function (num1 = 1, num2 =2)
{
return num1 * num2
}
//Arrow function
const multiply = (num1 = 1, num2 = 2)=> num1 * num2;
3. 简介主体
文档中给出了一个具体的例子:
错误示范:
const func = () => { foo: 1 };
// Calling func() returns undefined!
const func2 = () => { foo: function () {} };
// SyntaxError: function statement requires a name
const func3 = () => { foo() {} };
// SyntaxError: Unexpected token '{'
如果:=> (箭头)后面跟着的标记不是 {} (大括号),那么JS会认为箭头函数具有简洁主体,因此大括号内的语句才会被解析为语句。
正确用法:
const func = () => ({ foo: 1 });
不适用的情况
1. Cannot be used as method
2. No binding of arguments
3. Cannot be used as constructors
4. Cannot be used as generators