搞清 JS 中 this 的指向
this 是 JavaScript 中一个让人头疼的概念,它的指向在函数调用的不同场景下会发生变化。正确理解 this 的指向,可以帮助我们避免许多错误。在本文中,我们一起来理清 JS 中 this 的指向问题。
一、全局环境中的 this
在全局环境中,this 指向全局对象,在浏览器中就是 window 对象:
console.log(this === window); // true
需要注意的是,在 Node.js 中全局对象是 global,this 会指向 global。
二、函数内部的 this
对于一个普通的函数调用,函数内部的 this 同样指向全局对象:
function foo() {
console.log(this === window); // true
}
foo();
这个需要注意区分的是箭头函数,箭头函数内部的 this 与外部代码的 this 保持一致:
const obj = {
foo: () => {
console.log(this === window); // true
}
}
obj.foo();
三、对象方法中的 this
当函数被作为对象方法调用时,this 指向方法所属的对象:
const obj = {
name: 'Alice',
getName() {
return this.name;
}
};
obj.getName(); // 'Alice'
如果将方法单独提取出来,this 会指向全局对象:
const getName = obj.getName;
getName(); // ''
四、构造函数中的 this
在构造函数中,this 指向 newly 创建的对象:
function Foo() {
this.name = 'Foo';
}
const foo = new Foo();
foo.name; // 'Foo'
需要注意类的构造函数中的 this 同样指向新创建的实例。
五、call/apply/bind 调用中的 this
通过 call、apply 和 bind 改变 this 指向,this 会指向第一个参数对象:
const obj = {
name: 'Alice'
};
function foo() {
console.log(this.name);
}
foo.call(obj); // 'Alice'
总结
this 的指向是一个复杂的问题,不同的调用方式会导致它的指向发生变化。
掌握以下几点可以帮助我们正确处理 this:
- 全局环境中this指向全局对象
- 普通函数中this指向全局对象
- 对象方法中this指向该对象
- 构造函数中this指向新实例对象
- 使用call/apply/bind方法时this指向第一个参数
理清 this 指向,可以避免许多错误,也有助于我们写出更优雅的代码。