ES6箭头函数与this
- 首先看普通函数
const person = {
name: 'tom',
sayHi: function () {
console.log(`hi, my name is ${this.name}`);
}
}
person.sayHi();
- 输出结果:
hi, my name is tom
普通函数中,this指向调用者,this即person对象
- 使用箭头函数
const person = {
name: 'tom',
sayHi: () => {
// 这里的this指向箭头函数外、person内的this,即window,window.name=undefined
console.log(`hi, my name is ${this.name}`);
}
}
person.sayHi();
- 输出结果:
hi, my name is undefined
说明箭头函数中的this没有找到name属性
箭头函数在哪定义的,函数中的this就指向所在作用域中的this,即箭头函数外的this
- 异步执行函数时的this
const person = {
name: 'tom',
sayHiAsync: function () {
setTimeout(function () {
console.log(`hi, my name is ${this.name}`);
}, 1000);
}
}
person.sayHiAsync();
- 输出结果:
// 延迟1s后控制台打印
hi, my name is undefined
因为setTimeout
中的function
最终会被放到全局执行上下文中执行,此时的this指向window
- 解决方法1
定义一个变量保存当前作用域的this,也是利用了闭包机制
var tmp = 'window';
const person = {
name: 'tom',
sayHiAsync: function () {
const _this = this;
setTimeout(function () {
console.log(`hi, my name is ${_this.name}`);
}, 1000);
}
}
person.sayHiAsync(); // hi, my name is tom
- 解决方式2
使用箭头函数
const person = {
name: 'tom',
sayHiAsync: function () {
setTimeout(() => {
console.log(`hi, my name is ${this.name}`);
}, 1000);
}
}
person.sayHiAsync(); // hi, my name is tom
setTimeout
中的function函数体中的this指向的是上层函数体中的this,即sayHiAsync: function() {}
中的this,而这里的this取决于谁调用了它,person调用了sayHiAsync
,那么相当于person.name