ES6中允许使用"箭头"(=>)定义函数
var sum = ( a, b ) => a + b;
var sum = function( a, b ){
return a + b;
}
如果箭头函数的代码块部分多于一条语句,就要用大括号将它们括起来,并且使用return语句返回;
var sum = ( a, b ) => {
return a + b;
}
由于大括号被解释为代码块,所以箭头函数直接返回一个对象,必须在对象外面加上括号,否则报错;
//报错
var getItem = id => {
id: id,
name: "temp"
}
//不报错
var getItem = id => ({
id: id,
name: "temp"
})
箭头函数可以简化代码;
需注意:函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象;this对象的指向是可变的,但是在箭头函数中,它是固定的;
function foo(){
setTimeout(() => {
console.log("id:" + this.id)
},100)
}
var id = 21;
foo.call({id:42});//id: 42
//函数名.call()调用的时候必须传一个参数,只要不空着即可
function Timer() {
this.s1 = 0;
this.s2 = 0;
setInterval(() => this.s1++, 1000);
setInterval(function () {
this.s2++;
}, 1000);
}
var timer = new Timer();
setTimeout(() => console.log('s1: ', timer.s1), 3100);
setTimeout(() => console.log('s2: ', timer.s2), 3100);
//第一个定时器是箭头函数,this绑定定义时所在的作用域,是Timer函数,所以s1更新了3次 s1: 3
//第二个定时器是普通函数,this绑定定义时所在的作用域,是全局对象,所以s2更新了0次 s2: 0
箭头函数可以让this指向固定化,并不是因为箭头函数内部有绑定this的机制,实际原因是箭头函数根本没有自己的this,导致内部的this就是外层代码块的this(如下图)。除了this,以下三个变量在箭头函数之中也是不存在的,指向外层函数的对应变量:arguments、super、new.target;
// ES6
function foo() {
setTimeout(() => {
console.log('id:', this.id);
}, 100);
}
// ES5
function foo() {
var _this = this;
setTimeout(function () {
console.log('id:', _this.id);
}, 100);
}