理解 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, Rahul
  • this 指向 user,因为 usergreet()调用者

可视化表示

user → greet() → this = user

函数内部的 this

在普通函数中:

function sayHello() {
  console.log(this);
}

sayHello(); // Global object (window/global) or undefined in strict mode
  • 这里的 this 指向函数本身;它取决于 函数的调用方式

改变上下文:callapplybind

可以使用以下方法手动设置 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 22
  • call → 立即调用,参数逐个传入
  • 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显式设置的对象
0 浏览
Back to Blog

相关文章

阅读更多 »

理解 JavaScript 中的函数

什么是函数?函数是一段旨在执行特定任务的代码块。与其一次又一次地编写相同的代码,你可以只在内部编写一次。

执行上下文

想象 Execution Context 像一个厨房。在你开始烹饪(执行代码)之前,你需要工作空间、变量工具和函数配方。