有人说ES6(ES2015)最具魅力的是箭头函数。但真的,我不这么认为:箭头函数这玩意真是又丑又变扭!
![8ece7cbb3b7a2cc3444b633e6cc58b65.png](https://i-blog.csdnimg.cn/blog_migrate/5d6629457e1e60faac5b015db3641068.jpeg)
不过,箭头函数确实有它的功能优势:
1、简洁:
(虽然我也不认为这是真的简洁,还是认为它是很变扭的)
看一段代码:
const numbers = [1,2,3];
const event = numbers.filter(function(x){
return x % 2 === 0;
});
用箭头语法重写是这样的:
const numbers = [1,2,3];
const event = numbers.filter(x => x % 2 === 0);
(真是种稀里糊涂的格式,不易理解 -_-!)
解释:
function关键字被删除,只留下参数,紧跟着的是箭头(=>),然是函数功能体。
如果参数列表中包含多个参数,必须用括号包裹,并用逗号分割。
此外,没有参数时,必须在箭头前用一组空括号:()=>{...}。
当函数的主体只是一行时,可以不使用return,因为它是隐式应用的。
2、绑定的词法作用域
直接用例子来说明:
function DelayedGreeter(name){
this.name = name;
}
DelayedGreeter.prototype.greet = function(){
setTimeout(function cb(){
console.log("hello " + this.name);
},500);
}
const greeter = new DelayedGreeter("world");
greeter.greet();
在这段代码中,期望输出Hello world,但world参数并未能传到cb函数的,所以输出会是:
![5daa6635125006267a92afd5db5b4446.png](https://i-blog.csdnimg.cn/blog_migrate/805963f0a90fcbe4852d1a15e8809f0c.jpeg)
不引入箭头函数时,如果想要得到正确的输出,需要进行bind操作:
![1f45d5b8287f21e764e73b79571852d3.png](https://i-blog.csdnimg.cn/blog_migrate/8762bd3f79ab29d44681a5e31550b830.jpeg)
function DelayedGreeter(name){
this.name = name;
}
DelayedGreeter.prototype.greet = function(){
setTimeout( (function cb(){
console.log("hello " + this.name);
}).bind(this) ,500);
}
const greeter = new DelayedGreeter("world");
greeter.greet();
![66a574d6ec9f77014d7110c7b60d5e57.png](https://i-blog.csdnimg.cn/blog_migrate/cc1624b87cb757faab8a5c07652748a6.jpeg)
但如果使用箭头函数,由于它具有绑定作用域的特性,可以较方便的实现上述同样的效果:
![08f2184250c39101fd0b4de3ad435d12.png](https://i-blog.csdnimg.cn/blog_migrate/dbfefbda88a21141c17fa2d88a0d5e36.jpeg)
function DelayedGreeter(name){
this.name = name;
}
DelayedGreeter.prototype.greet = function(){
setTimeout( ()=> console.log("hello " + this.name) ,500);
}
const greeter = new DelayedGreeter("world");
greeter.greet();
在这个方面的应用确实是方便了一些。