引入箭头函数有两个方面的作用:更简短的函数并且不绑定this;
1、更简短的函数
var materials = [ 'Hydrogen', 'Helium', 'Lithium', 'Beryllium'];materials.map(function(material) { return material.length; }); // [8, 6, 7, 9]materials.map((material) => { return material.length;}); // [8, 6, 7, 9]materials.map(material => material.length); // [8, 6, 7, 9]
箭头函数相当于匿名函数,并且简化了函数定义。箭头函数有两种格式,一种像上面的,只包含一个表达式,连{ ... }
和return
都省略掉了。还有一种可以包含多条语句,这时候就不能省略{ ... }
和return
:
// 可变参数:(x, y, ...rest) => { var i, sum = x + y; for (i=0; i
如果要返回一个对象,就要注意,如果是单表达式,这么写的话会报错:
// SyntaxError:x => { foo: x }
因为和函数体的{ ... }
有语法冲突,所以要改为:
// ok:x => ({ foo: x })
2、不绑定this
在箭头函数出现之前,每个新定义的函数都有它自己的 值(在构造函数的情况下是一个新对象,在严格模式的函数调用中为 undefined,如果该函数被称为“对象方法”则为基础对象等。
例1️⃣
function Person() { // The Person() constructor defines `this` as an instance of itself. this.age = 0; console.log(this); //Person {age: 0} setInterval(function growUp() { // In non-strict mode, the growUp() function defines `this` // as the global object, which is different from the `this` // defined by the Person() constructor. console.log(this) //window console.log(this.age) //undefined this.age++; }, 1000);}var p = new Person();
在ECMAScript 3/5中,通过将this
值分配给封闭的变量,可以解决this
问题。
function Person() { var that = this; that.age = 0; console.log(this,11);//Person{age:0} setInterval(function growUp() { // The callback refers to the `that` variable of which // the value is the expected object. console.log(that.age); that.age++; }, 1000);}var p = new Person();
箭头功能不会创建自己的this
;它使用封闭执行上下文的this
值。因此,在下面的代码中,传递给setInterval
的函数内的this
与封闭函数中的this
值相同:
function Person(){ this.age = 0; setInterval(() => { this.age++; // |this| properly refers to the person object }, 1000);}var p = new Person();
综上:在普通函数中,this指向window;在构造函数中,this指向new的实例;在setinterval中,this指向window,而此时箭头函数中,this指向封闭函数中的this。
3、箭头函数的其他适用环境
// An empty arrow function returns undefinedlet empty = () => {};(() => 'foobar')(); // Returns "foobar"// (this is an Immediately Invoked Function Expression // see 'IIFE' in glossary)var simple = a => a > 15 ? 15 : a; simple(16); // 15simple(10); // 10let 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); // 66var even = arr.filter(v => v % 2 == 0); // [6, 0, 18]var double = arr.map(v => v * 2); // [10, 12, 26, 0, 2, 36, 46]// More concise promise chainspromise.then(a => { // ...}).then(b => { // ...});// Parameterless arrow functions that are visually easier to parsesetTimeout( () => { console.log('I happen sooner'); setTimeout( () => { // deeper code console.log('I happen later'); }, 1);}, 1);
推荐相关文章:
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_functions
https://juejin.im/entry/584fa735128fe100692e9f02 https://www.liaoxuefeng.com/wiki/001434446689867b27157e896e74d51a89c25cc8b43bdb3000/001438565969057627e5435793645b7acaee3b6869d1374000