ES6的箭头函数对this
关键字的绑定的改进老生常谈了。不再赘述,这里仅仅尝试一下改进的甜头。
下面片段对比了实用arrow function和不使用的区别:
class Person {
constructor(firstname, lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
getName() {
setTimeout(() => {
console.log(this.firstname, this.lastname);
}, 1000);
}
getNameV2() {
setTimeout(function() {
console.log(this.firstname, this.lastname);
}, 1000);
}
}
var p = new Person('jianyong', 'lee');
p.getName(); // jianyong lee
p.getNameV2(); // undefined undefined
注意到p.getNameV2()
没有正确输出,“衬托”出了arrow function的“强大”。
那么在ES5中以及之前的js版本中,如何处理这个情况呢?老一辈的jser能工巧匠实用下面方法解决:
1. 使用bind函数
getNameV3() {
setTimeout(function() {
console.log(this.firstname, this.lastname);
}.bind(this), 1000);
}
- 保存
this
引用
getNameV3() {
var ctx = this;
setTimeout(function() {
console.log(ctx.firstname, ctx.lastname);
}.bind(this), 1000);
}