ES6的箭头函数应该是ES6标准里我接触比较多的,看过几篇文章,现在对箭头函数自己做一个总结。
阮一峰老师的ES6介绍里面的《函数的扩展》关于箭头函数的介绍,还是相当详细。
结合从 use strict 看 JS(一):this 与箭头函数一文,写写我关于箭头函数的理解。
this的调用方式
- 函数作为对象方法,在对象方法内使用this
var obj = {
name: 'objName',
getName: function(){
return this.name;// 在此处使用this,叫做方法调用
}
}
- 在函数里面调用
function func(){
return this.name;
}
这里的this指向的是window对象(如果是在全局调用的话),但在严格模式里,这个this表示undefined。
- 在构造函数中使用,构造函数与普通函数的区别就是new关键字。
function constructor(name){
this.name = name;
}
var amy = new constructor('Amy');
this指向的是new出来的对象实例。
- 使用apply/call/bind改变this指向
箭头函数
主要的用法就不再说了,说说其特点和需要注意的地方。
- 函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。
这里可以使用ES6和ES5的两种方式,看看实现效果
//ES6
function timer(){
setTimeout(()=>{console.log(this.name);}, 1000);
}
timer.call({name: 'amy'}); //输出amy
//ES5
name = 'tom';
function timer(){
setTimeout(function(){console.log(this.name)}, 1000);
}
timer.call({name: 'amy'}) //输出tom
箭头函数可以让setTimeout里面的this,绑定定义时所在的作用域,而不是指向运行时所在的作用域。
- 箭头函数里没有this
箭头函数中,没有this。如果你在箭头函数中使用了this,那么该this一定就是外层的this。
//错误, this为undefined/window
const person = {
name: 'tom',
getName: ()=>this.name;// == return undefined.name/window.name
}
// 可以稍做改动
const person = {
name: 'tom',
getName: function() {
return setTimeout(() => this.name, 1000);
}
}
// 编译之后变成
var person = {
name: 'tom',
getName: function getName() {
var _this = this; // 使用了我们在es5时常用的方式保存this引用
return setTimeout(function () {
return _this.name;
}, 1000);
}
};
为什么第一个代码段里的this为undefined呢?
是因为,箭头函数默认使用的是严格模式,严格模式中是匿名函数中的this指向的不再是window了,而是undefined。
即便不是undefined,那也是window。
箭头函数里面根本没有自己的this,而是引用外层的this。
- 不存在arguments参数
在箭头函数中是没有arguments参数的,这点和this一样。
function getMsg(msg){
setTimeout(()=>console.log(arguments[0]));
}
getMsg('hi');//输出hi