箭头函数(Arrows), 是用新的 => 语法书写的匿名函数, 如:javascript
[1, 2, 3].map(n => n + 1);
等同于下面使用ES5的写法:java
[1, 2, 3].map(function(n) { return n + 1; });
可能一开始没法接受,但慢慢的会发现箭头函数带来的快感不言而喻。做为一个PHP后端人士但愿PHP也能支持该语法, ?。后端
通常写法, 如计算两个数字之和, 并返回:函数
(arg1, arg2) => { let arg3 = arg1 + arg2 return arg3 }
不用写function关键字, 可是上面的写法,也感受不出来有多少简化,咱们来看看几种状况:this
若是只有一个参数,能够不用写括号code
n => { return n + 1 }
等价于ip
(n) => { return n + 1 }
若是函数只有一行执行代码,能够省去花括号,写在一行文档
n => alert(n)
等价于io
n => { alert(n) }
写在一行的时候,也能够省略return关键字console
n => n + 1
等价于
n => { return n + 1 }
没有参数的时候,则必须用(), 如
() => alert('ES2015 Rocks!');
语法介绍完毕,须要特别强调并指出的是:
和用function关键字命名的函数不一样的是,箭头函数体内和它的所在的块区域共享同一个this , 举个例子:
直接在Chrome Console中运行如下代码:
class Zoo { constructor(name, animals = []) { this.name = name; this.animals = animals; } list() { this.animals.map(animal => { console.log(this.name + '里有' + animal); }); } list2() { this.animals.map(function() { console.log(this.name + '里有' + animal); }); } } let zoo = new Zoo('小红山动物园', ['大象', '猴子', '长颈鹿']); zoo.list(); zoo.list2();
以上代码输出:
> 小红山动物园里有大象 > 小红山动物园里有猴子 > 小红山动物园里有长颈鹿 > Uncaught TypeError: Cannot read property 'name' of undefined(…)
这就是文档中所说的:
Unlike functions, arrows share the same lexical this as their surrounding code.
相信你也已经掌握箭头函数的用法了吧?欢迎继续浏览下一章节。