贝利信息

Javascript中的this关键字在不同上下文中如何指向?

日期:2026-01-10 00:00 / 作者:幻影之瞳
JavaScript 中的 this 值取决于函数调用方式而非定义方式:普通调用时非严格模式指向全局对象、严格模式为 undefined;箭头函数继承外层 this;方法调用时指向点号左侧对象;构造调用时指向新实例;call/apply/bind 可显式绑定 this。

JavaScript 中的 this 不指向函数本身,也不固定指向某个对象——它的值完全取决于函数「怎么被调用」,而不是「怎么被定义」。理解这点是避免常见 bug 的关键。

普通函数调用时,this 指向全局对象或 undefined

在非严格模式下,直接调用函数(如 foo()),this 指向全局对象(浏览器中是 window,Node.js 中是 global);严格模式下则为 undefined

function foo() {
  console.log(this);
}
foo(); // 非严格模式 → window;严格模式 → undefined

方法调用时,this 指向调用它的对象

当函数作为对象的属性被调用(即 obj.method()),this 绑定到该对象。

const obj = {
  name: 'Alice',
  greet() {
    console.log(`Hello, ${this.name}`);
  }
};
obj.greet(); // Hello, Alice

构造函数与 class 中,this 指向新创建的实例

new 调用函数时,引擎会自动创建空对象,并将 this 绑定到它;class 构造器内部的 this 同理。

function Person(name) {
  this.name = name; // this 指向 new 出来的实例
}
const p = new Person('Bob');

class Animal {
  constructor(type) {
    this.type = type; // this 指向 new Animal() 实例
  }
}

显式绑定:call、apply、bind 改变 this 指向

这三个方法允许你手动指定函数执行时的 this 值。其中 bind 返回新函数,callapply 立即执行。

function logInfo() {
  console.log(this.id, this.msg);
}
const ctx = { id: 42, msg: 'ok' };
logInfo.call(ctx);     // 42 'ok'
logInfo.apply(ctx);    // 同上
const bound = logInfo.bind(ctx);
bound();               // 42 'ok'

真正难的不是记住规则,而是识别「调用形式是否发生了隐式转换」——比如 array.forEach(obj.method) 中的 obj.method 已经脱离了 objthis 会丢失。这类问题往往只在运行时暴露,调试时要盯住调用链最末端的那个点操作。