The arrow function is a shorthand function expression, and it has the this value of the lexical scope (that is, it will not create new objects such as this, arguments, super and new.target in its own scope). Additionally, arrow functions are always anonymous.
Basic Grammar
(param1, param2, …, paramN) => { statements } (param1, param2, …, paramN) => expression // equivalent to: => { return expression; } // 如果只有一个参数,圆括号是可选的: (singleParam) => { statements } singleParam => { statements } // 无参数的函数需要使用圆括号: () => { statements }
Advanced Grammar
// 返回对象字面量时应当用圆括号将其包起来: params => ({foo: bar}) // 支持 Rest parameters 和 default parameters: (param1, param2, ...rest) => { statements } (param1 = defaultValue1, param2, …, paramN = defaultValueN) => { statements } // Destructuring within the parameter list is also supported var f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c; f(); // 6
Description
The introduction of arrow functions has two impacts: one is shorter function writing, and the other is lexical analysis of this.
In some functional programming patterns, shorter functions are very popular. Try to compare:
var a = [ "Hydrogen", "Helium", "Lithium", "Beryllium" ]; var a2 = a.map(function(s){ return s.length }); var a3 = a.map( s => s.length );
Before the arrow function, each newly defined function had its own this Value (for example, the this of a constructor points to a new object; the this value of a function in strict mode is undefined; if a function is called as a method of an object, its this points to the object that called it). In object-oriented programming, this can prove to be very annoying.
function Person() { // 构造函数 Person() 定义的 `this` 就是新实例对象自己 this.age = 0; setInterval(function growUp() { // 在非严格模式下,growUp() 函数定义了其内部的 `this` // 为全局对象, 不同于构造函数Person()的定义的 `this` this.age++; }, 1000); } var p = new Person();
In ECMAScript 3/5, this problem can be solved by adding a variable to point to the desired this object, and then placing the variable in the closure.
function Person() { var self = this; // 也有人选择使用 `that` 而非 `self`. // 只要保证一致就好. self.age = 0; setInterval(function growUp() { // 回调里面的 `self` 变量就指向了期望的那个对象了 self.age++; }, 1000); }
In addition, you can also use the bind function to pass the expected this value to the growUp() function.
The arrow function will capture the this value of its context as its own this value, so the following code will run as expected.
function Person(){ this.age = 0; setInterval(() => { this.age++; // |this| 正确地指向了 person 对象 }, 1000); } var p = new Person();
Considering that this is at the lexical level, all rules related to this in strict mode will be neglect.
var f = () => {'use strict'; return this}; f() === window; // 或全局对象
Other rules of strict mode remain unchanged.
Since this is already in the lexical The binding is completed at the level. When calling a function through the call() or apply() method, only the parameters are passed in, and it has no impact on this:
<span style="font-size:14px;">var adder = { base : 1, add : function(a) { var f = v => v + this.base; return f(a); }, addThruCall: function(a) { var f = v => v + this.base; var b = { base : 2 }; return f.call(b, a); } }; console.log(adder.add(1)); // 输出 2 console.log(adder.addThruCall(1)); // 仍然输出 2(而不是3 ——译者注)</span>
The arrow function will not expose the arguments object inside it: arguments.length, arguments[0], arguments[1], etc., will not point to the arguments of the arrow function. Instead, it points to a value named arguments in the scope where the arrow function is located (if any, otherwise, it is undefined).
var arguments = 42; var arr = () => arguments; arr(); // 42 function foo() { var f = () => arguments[0]; // foo's implicit arguments binding return f(2); } foo(1); // 1
The arrow function does not have its own arguments object, but in most cases, the rest parameter can give a solution:
function foo() { var f = (...args) => args[0]; return f(2); } foo(1); // 2
As mentioned above, arrow function expressions are most appropriate for functions without method names. Let’s see What happens when we try to use them as methods.
'use strict'; var obj = { i: 10, b: () => console.log(this.i, this), c: function() { console.log( this.i, this) } } obj.b(); // prints undefined, Window obj.c(); // prints 10, Object {...}
箭头函数没有定义this绑定。
'use strict'; var obj = { a: 10 }; Object.defineProperty(obj, "b", { get: () => { console.log(this.a, typeof this.a, this); return this.a+10; // represents global object 'Window', therefore 'this.a' returns 'undefined' } });
使用new操作符
箭头函数不能用作构造器,和 new 一起用就会抛出错误。
yield关键字通常不能在箭头函数中使用(except when permitted within functions further nested within it)。因此,箭头函数不能用作Generator函数。
请牢记,用 params => {object:literal} 这种简单的语法返回一个对象字面量是行不通的:
var func = () => { foo: 1 }; // Calling func() returns undefined! var func = () => { foo: function() {} }; // SyntaxError: function statement requires a name
这是因为花括号(即 {} )里面的代码被解析为声明序列了(例如, foo 被认为是一个 label, 而非对象字面量里的键)。
所以,记得用圆括号把对象字面量包起来:
var func = () => ({ foo: 1 });
换行
箭头函数在参数和箭头之间不能换行哦
var func = () => 1; // SyntaxError: expected expression, got '=>'
解析顺序
在箭头函数中的箭头不是操作符(或者运算符,就像'+ -'那些), 但是 箭头函数有特殊的解析规则就是:相比普通的函数, 随着操作符优先级不同交互也不同(建议看英文版)。
let callback; callback = callback || function() {}; // ok callback = callback || () => {}; // SyntaxError: invalid arrow-function arguments callback = callback || (() => {}); // ok
示例
// 一个空箭头函数,返回 undefined let empty = () => {}; (() => "foobar")() // 返回 "foobar" var simple = a => a > 15 ? 15 : a; simple(16); // 15 simple(10); // 10 let max = (a, b) => a > b ? a : b; // Easy array filtering, mapping, ... var arr = [5, 6, 13, 0, 1, 18, 23]; var sum = arr.reduce((a, b) => a + b); // 66 var even = arr.filter(v => v % 2 == 0); // [6, 0, 18] var double = arr.map(v => v * 2); // [10, 12, 26, 0, 2, 36, 46] // 更多简明的promise链 promise.then(a => { // ... }).then(b => { // ... });
The above is the detailed content of Introduction to arrow functions in js. For more information, please follow other related articles on the PHP Chinese website!