箭头函数应用场景
箭头函数在ES6的标准中被引入,可用于替代传统定义函数的写法,一般用在函数本身代码量较少,且处理逻辑简单的场景,此时可以用箭头函数替代掉原有函数的写法。但是如果函数的代码量较大以及处理逻辑较为复杂的时候还是使用传统的函数定义方法。
简化函数的定义
编写一个立即执行的函数,传统定义方式
!function(){
console.log('hello world');
}();
使用箭头函数
(()=>{console.log('hello world');})();
函数作为参数传递
传统的做法
[1,2,3].map(function(x){
return x*x;
});
使用箭头函数
[1,2,3].map((x)=>{return x*x;});
更简单的写法
[1,2,3].map((x)=>x*x);//函数体中只有一个return 所以可以去掉花括号以及return,只写需要计算返回值的表达式
简化函数执行上下文绑定的方式
this在js里面使用场景较多,切换也比较频繁,因此带来了各种运行时因为上下文切换导致错误,如下代码:
function c(){
this.test = 'hello';
this.print = function(){
setTimeout(function(){console.log(this.test);},1000);
}
}
var m = new c();
m.print();
由于使用了setTimeout
在1000ms以后执行console中的内容,此时this已经不代表c对象实例,此时this为全局的this,所以运行时输出undefined。此种情况下传统的做法可以使用Function.prototype.bind
将执行的上下文绑定在函数上面
function c(){
this.test = 'hello';
this.print = function(){
setTimeout(function({console.log(this.test);}.bind(this),1000);
}
}
var m = new c();
m.print();
能够正常的输出值
使用箭头函数可以让这一过程更简单
function c(){
this.test = 'hello';
this.print = function(){
setTimeout(()=>{console.log(this.test);},1000);
}
}
var m = new c();
m.print();