JavaScript的this由运行时调用上下文决定:普通函数直接调用时指向全局对象(非严格模式)或undefined(严格模式);对象方法调用时指向调用者对象;call/apply/bind可显式绑定;箭头函数继承外层this;new调用时指向新实例。

JavaScript 的 this 不是指向定义时的词法作用域,而是运行时调用上下文决定的——这是绝大多数困惑的根源。
普通函数调用时的 this 指向全局对象(非严格模式)或 undefined(严格模式)
直接调用函数,不通过对象属性或 call/apply/bind,this 就“掉”到最外层:
- 在浏览器中,非严格模式下是
window;严格模式下是undefined - Node.js 中对应
global或undefined,逻辑一致 - 箭头函数不绑定
this,它沿用外层函数的this,但普通函数不会“继承”,只看谁调用它
function foo() {
console.log(this);
}
foo(); // 浏览器非严格模式 → window;严格模式 → undefined
对象方法调用时 this 指向调用它的那个对象
关键不是“写在哪”,而是“谁点的”。只要形如 obj.method(),this 就是 obj:
- 即使把方法赋值给变量再调用,也会丢失绑定:
const fn = obj.method; fn();→this不再是obj - 嵌套对象也一样:
obj.inner.nestedMethod()→this是obj.inner,不是obj - 原型链上的方法同理:
obj.method()即使method在Object.getPrototypeOf(obj)上,this仍是obj
const obj = {
name: 'test',
say() {
console.log(this.name); // 'test'
}
};
obj.say(); // this → obj
const sayRef = obj.say;
sayRef(); // this → global/undefined(丢失绑定)
call、apply、bind 显式控制 this
它们不改变函数本身,只在调用瞬间或生成新函数时覆盖默认绑定规则:
立即学习“Java免费学习笔记(深入)”;
-
fn.call(obj, arg1, arg2):立即执行,this强制为obj -
fn.apply(obj, [arg1, arg2]):参数以数组传入,this同样为obj -
fn.bind(obj):返回一个新函数,无论之后怎么调用,this永远锁定为obj - 注意:
bind绑定不可被后续的call/apply覆盖(除非用new)
function log(x) { console.log(this.value, x); }
const ctx = { value: 42 };
log.call(ctx, 'hello'); // 42 'hello'
const bound = log.bind({ value: 99 });
bound('world'); // 99 'world'
构造函数和类方法中的 this 指向新实例
用 new 调用函数时,this 自动绑定为新创建的对象;类的 constructor 和普通方法也遵循这一逻辑:
- 类方法内部的
this默认指向实例,但若被单独提取(如作为事件回调),仍会丢失,需手动绑定 - 箭头函数在类字段中常用于避免绑定问题:
handler = () => { console.log(this.value); } -
new优先级最高:即使函数已被bind过,new boundFn()仍会创建新实例并让this指向它
class Counter {
constructor() {
this.count = 0;
}
inc() {
this.count++;
}
}
const c = new Counter();
c.inc(); // this → c
const incRef = c.inc;
incRef(); // this → undefined(严格模式),不是 c
真正容易忽略的是:this 的绑定发生在“调用时刻”,而非定义或赋值时刻;所有绑定方式(隐式、显式、new、箭头函数)之间有明确的优先级顺序,混用时务必确认哪一层生效了。











