理解 JavaScript 中的 this 关键字
发布: (2026年4月4日 GMT+8 13:47)
3 分钟阅读
原文: Dev.to
Source: Dev.to
介绍
JavaScript 有一个经常让初学者感到困惑的特殊关键字 this。
核心思想:this 指向“调用”函数的对象。
全局上下文中的 this
在全局作用域中:
// In a browser → points to `window` object
// In Node.js → points to `global` object可视化:
全局作用域 →this = window(浏览器)/global(Node)
对象内部的 this
当函数作为对象的方法被调用时,this 指向该对象。
const user = {
name: "Rahul",
greet() {
console.log(`Hello, ${this.name}`);
}
};
user.greet(); // Hello, Rahulthis指向user,因为user是greet()的 调用者。
可视化表示
user → greet() → this = user函数内部的 this
在普通函数中:
function sayHello() {
console.log(this);
}
sayHello(); // Global object (window/global) or undefined in strict mode- 这里的
this不指向函数本身;它取决于 函数的调用方式。
改变上下文:call、apply、bind
可以使用以下方法手动设置 this:
const user = { name: "Rahul" };
function greet(age) {
console.log(`${this.name} is ${age} years old`);
}
greet.call(user, 22); // Rahul is 22
greet.apply(user, [22]); // Rahul is 22
const boundGreet = greet.bind(user);
boundGreet(22); // Rahul is 22call→ 立即调用,参数逐个传入apply→ 立即调用,参数以数组形式传入bind→ 返回一个新函数,this被绑定到指定对象
箭头函数中的 this
箭头函数没有自己的 this;它们从外层(词法)作用域继承 this。
const user = {
name: "Rahul",
greet: () => {
console.log(this.name);
}
};
user.greet(); // undefined (inherits `this` from global scope, not `user`)关键要点
this指向 函数的调用者,而不是函数本身。- 全局上下文 → 指向
window(浏览器)或global(Node)。 - 对象方法 → 指向调用该方法的对象。
- 普通函数 → 全局对象(在严格模式下为
undefined)。 - 箭头函数 → 从外层词法作用域继承
this。
上下文速查表
| 上下文 | this 指向 |
|---|---|
| 全局 | window / global |
| 对象方法 | 调用该方法的对象 |
| 普通函数 | 全局对象(或严格模式下的 undefined) |
| 箭头函数 | 外层词法作用域 |
call/apply/bind | 显式设置的对象 |