语法
([param] ,[ param]) => {
statements
}
param => expression
- 1
- 2
- 3
- 4
- 5
首先我们看参数部分有这样三种情况:
1.没有参数 () => {…}
2.多个参数 (a,b) => {…}
3.一个参数 () => {…}
返回值有两种情况:带{}和不带{}
示例
参数:
1.没有参数
() => a+b
//function(){return a + b};
2.多个参数
(c,d) => c-d
//function(c,d){return c - d}
3.一个参数
(name)=> name
//function(name){return name}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
返回值:
1.多行表达式用{}括起来,当大括号里面有return则有return,没有则没有
2.单行表达式不用{}括起来,自带return
1.多行表达式有return
() => {
let a = 1,b = 2;
return a+b;
}
//function(){let a=1,b=2;return a+b}
2.多行表达式不带有return
() => {
let a = 1,b = 2;
a = a + b;
}
//function(){
// let a=1,b=2;
// a=a+b
//}
3.单行表达式不带return
(a) => a+3;//function(a){return a+3}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
特性
箭头函数内部没有constructor方法,也没有prototype,所以不支持new操作。但是它对this的处理与一般的普通函数不一样。箭头函数的 this 始终指向函数定义时的 this,而非执行时。我们通过一个例子来理解:
var qing = {
x : 1,
func : function() { console.log(this.x) },
test : function() {
setTimeout(function() {
this.func();
}, 100);
}
};
qing.test(); // TypeError : this.func is not a function
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
setTimeout下面的函数改变了函数的执行队列,所以他下面的函数的this是window
我们可以改写一下
var qing = {
x : 1,
func : function() { console.log(this.x) },
test : function() {
var that = this;
setTimeout(function() {
that.func();
}, 100);
}
};
qing.test();
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
所以说箭头函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。
箭头函数的 this 始终指向函数定义时的 this,而非执行时,所以箭头函数的this指向是固定的
var qing = {
x : 1,
func : function() { console.log(this.x) },
test : function() {
setTimeout(() => { this.func() }, 100);
}
};
qing.test();
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
这时this就一直指向qing这个对象了
箭头函数可以让this指向固定化,这种特性很有利于封装回调函数。下面是一个例子,DOM 事件的回调函数封装在一个对象里面。
var handler = {
id: '123456',
init: function() {
document.addEventListener('click',
event => this.doSomething(event.type), false);
},
doSomething: function(type) {
console.log('Handling ' + type + ' for ' + this.id);
}
};
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
上面代码的init方法中,使用了箭头函数,这导致这个箭头函数里面的this,总是指向handler对象。否则,回调函数运行时,this.doSomething这一行会报错,因为此时this指向document对象。
this指向的固定化,并不是因为箭头函数内部有绑定this的机制,实际原因是箭头函数根本没有自己的this,导致内部的this就是外层代码块的this。正是因为它没有this,所以也就不能用作构造函数。