普通函数内部的this指向的是函数运行时所在的对象,this指向是可变的:
const person = {
name: 'Lily',
sayHi: function () {
console.log(`This is ${this.name}`);
}
}
person.sayHi(); // This is Lily
箭头函数内部没有自己的this对象,内部的this就是函数定义生效时其上层作用域中的this:
const person = {
name: 'Lily',
sayHi: () => {
console.log(this); // {}
console.log(`This is ${this.name}`);
}
}
console.log(person.this); // undefined
person.sayHi(); // This is undefined
--------------------------------------------------------------------------------------------------------------------------------
普通函数this指向的可变性:
const person = {
name: 'Lily',
sayHiAsync: function () {
console.log(this);
setTimeout(function () {
console.log(this);
console.log(this.name);
}, 1000)
}
}
person.sayHiAsync();
// 输出结果为:
// { name: 'Lily', sayHiAsync: [Function: sayHiAsync] }
// Timeout {
// _idleTimeout: 1000,
// _idlePrev: null,
// _idleNext: null,
// _idleStart: 48,
// _onTimeout: [Function],
// _timerArgs: undefined,
// _repeat: null,
// _destroyed: false,
// [Symbol(refed)]: true,
// [Symbol(asyncId)]: 6,
// [Symbol(triggerId)]: 1
// }
// undefined
// 改变this指向的可变性const _this = this:
const person = {
name: 'Lily',
sayHiAsync: function () {
console.log(this);
const _this = this;
setTimeout(function () {
console.log(this);
console.log(_this.name);
}, 1000)
}
}
person.sayHiAsync();
// 输出结果为:
// { name: 'Lily', sayHiAsync: [Function: sayHiAsync] }
// Timeout {
// _idleTimeout: 1000,
// _idlePrev: null,
// _idleNext: null,
// _idleStart: 46,
// _onTimeout: [Function],
// _timerArgs: undefined,
// _repeat: null,
// _destroyed: false,
// [Symbol(refed)]: true,
// [Symbol(asyncId)]: 6,
// [Symbol(triggerId)]: 1
// }
// Lily
箭头函数中this指向的固定性:
const person = {
name: 'Lily',
sayHiAsync: function () {
console.log(this);
setTimeout(() => {
console.log(this);
console.log(this.name);
}, 1000)
}
}
person.sayHiAsync();
// 输出结果为:
// { name: 'Lily', sayHiAsync: [Function: sayHiAsync] }
// { name: 'Lily', sayHiAsync: [Function: sayHiAsync] }
// Lily