this 指向哪里?
一般来说,在 JS 中,谁来调用 this 所在函数,那 this 就指向谁
箭头函数中的 this 指向它所在函数的外层作用域
普通函数中的 this 指向 window
function func() {
console.log(this);
}
func(); // window
实例化构造函数中的 this 指向实例
function Person() {}
Person.prototype.sayHi = function () {
console.log(this);
};
const p = new Person();
p.sayHi(); // p
接上面,如果将 sayHi 的引用赋给另一个变量
function Person() {}
Person.prototype.sayHi = function () {
console.log(this);
};
const p = new Person();
const k = p.sayHi;
k(); // 因为这里是由全局作用域来调用,所以打印出 this 就是window
再接上面,如果用 ES6 语法 class 来声明对象
class Person {
sayHi() {
console.log(this);
}
}
const p = new Person();
const sayHiccc = p.sayHi;
sayHiccc(); // 这里也是全局作用域来调用,但由于ES6语法默认采用严格模式,this 不会指向 window,所以是undefined
为了证明严格模式全局环境下,this 不指向 window:
'use strict'; // 注意这里
function Person() {}
Person.prototype.sayHi = function () {
console.log(this);
};
const p = new Person();
const k = p.sayHi;
k(); // 这里打印的就是 undefined 了
对象中普通函数和箭头函数的 this 差异
普通函数中 this 是
动
态绑定的,指向执行时
所在环境箭头函数中 this 是
静
态绑定的,指向定义之初
所在环境
一个定时器的案例:
class Obj {
interval() {
setTimeout(function () {
console.log('普通函数', this); // 2秒后在全局window中调用,所以指向window
}, 2000);
setTimeout(() => {
console.log('箭头函数', this); // 定义时,这里 this 指向上层,被实例化后指向实例对象 o
}, 3000);
}
}
const o = new Obj();
o.interval();