箭头函数包含以下几个内容:
1 箭头函数的基本用法
2 使用箭头函数注意事项
3 箭头函数的 this
4 不适用箭头函数的场合
5 嵌套的箭头函数
下面是每个内容详情:
1 箭头函数的基本用法
//ES5 普通函数
var function foo(e){
return e;
}
//ES6 箭头函数
var foo = e => e;
如果箭头函数的参数是一个参数那么可以直接写成上面那种格式
当箭头函数的参数不是一个参数,或者没有参数的时候,写法如下:
// 没有参数的时候
let foo = () => 1;
//不止一个参数的时候
let foo = (a,b,c) => a + b + c;
如果箭头函数的代码块部分只有一条语句的话,可以像上面那种写法
当箭头函数代码块多于一条语句时,就要用大括号把他们包起来,并且要使用 return 返回语句
let foo = (a,b,c) => {return a + b + c;}
但是如果箭头函数代码块直接返回一个对象,必须在对象外面用大括号括起来,否则会报错。
// 报错
let getTempItem = id => { id: id, name: "Temp" };
// 不报错
let getTempItem = id => ({ id: id, name: "Temp" });
2 使用箭头函数注意事项
箭头函数有几个使用注意点。
(1)函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。
(2)不可以当作构造函数,也就是说,不可以使用new命令,否则会抛出一个错误。
(3)不可以使用arguments对象,该对象在函数体内不存在。如果要用,可以用 rest 参数代替。
(4)不可以使用yield命令,因此箭头函数不能用作 Generator 函数。
(5)arguments、super、new.target 在箭头函数之中也是不存在的,指向外层函数的对应变 量:arguments、super、new.target
(6)由于箭头函数没有自己的this,所以当然也就不能用call()、apply()、bind()这些方法去改变this的指向。
3 箭头函数的 this
箭头函数没有自己的 this 在普通函数中 this 指向是可变的,在箭头函数中 this 是固定化的。
function foo() {
setTimeout(() => {
console.log('id:', this.id);
}, 100);
}
var id = 21;
foo.call({ id: 42 });
// id: 42
箭头函数 this 它绑定定义时的作用域,而不是指向运行时的作用域。
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);
// s1: 3
// s2: 0
当在对象的方法中使用箭头函数 箭头函数的 this 就指向该对象
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);
}
};
//在init方法中,使用了箭头函数,这导致这个箭头函数里面的this,总是指向handler对象。否则,回调函数运行时,this.doSomething这一行会报错,因为此时this指向document对象。
4 不适用箭头函数的场合
(1)定义对象的方法时不适合用箭头函数。
const cat = {
lives: 9,
jumps: () => {
this.lives--;
}
}
console.log(cat.jumps()) //undefined
(2)需要动态 this 的时候,也适用箭头函数。
var button = document.getElementById('press');
button.addEventListener('click', () => {
this.classList.toggle('on');
});
//运行时,点击按钮会报错,因为button的监听函数是一个箭头函数,导致里面的this就是全局对象。如果改成普通函数,this就会动态指向被点击的按钮对象。
(3)如果函数体很复杂,有许多行也不适合用箭头函数。
5 嵌套的箭头函数
箭头函数内部可以在使用箭头函数嵌套。
//使用 ES6 箭头函数
let insert = (value) => ({into: (array) => ({after: (afterValue) => {
array.splice(array.indexOf(afterValue) + 1, 0, value);
return array;
}})});
insert(2).into([1, 3]).after(1); //[1, 2, 3]
//使用 ES5 普通函数
function insert(value) {
return {into: function (array) {
return {after: function (afterValue) {
array.splice(array.indexOf(afterValue) + 1, 0, value);
return array;
}};
}};
}
insert(2).into([1, 3]).after(1); //[1, 2, 3]