JavaScript中this指向由调用上下文决定:对象方法调用时指向调用者;箭头函数无this,继承外层;call/apply/bind可显式绑定;构造函数和class中this指向新实例。

在 JavaScript 中,this 的指向不是由函数定义时决定的,而是由**函数被调用时的上下文**决定的。简单说:谁调用这个方法,this 就指向谁(绝大多数情况下),但有几个关键细节必须注意。
普通对象方法调用:this 指向调用者
当一个函数作为对象的属性被调用时,this 自动绑定到该对象。
const obj = {
name: 'Alice',
greet() {
console.log(`Hello, I'm ${this.name}`);
}
};
obj.greet(); // Hello, I'm Alice → this 指向 obj
- 关键看调用形式:
obj.greet()是“点号调用”,this 绑定到点号前的对象(obj) - 如果把方法单独提取出来再调用,就失去绑定:
const fn = obj.greet; fn();此时 this 指向全局对象(非严格模式)或 undefined(严格模式)
箭头函数没有自己的 this
箭头函数不创建自己的 this,它会沿作用域链向上查找,继承外层函数的 this 值。
const obj = {
name: 'Bob',
regular() {
console.log(this.name); // Bob
const arrow = () => console.log(this.name); // 也输出 Bob
arrow();
}
};
- 箭头函数的 this 是静态的,定义时就确定了,和调用方式无关
- 不能用
call、apply、bind改变箭头函数的 this - 适合用在回调中避免 this 丢失,比如事件监听或定时器
显式绑定:call / apply / bind
你可以用 call、apply 或 bind 强制指定 this 的值。
立即学习“Java免费学习笔记(深入)”;
function introduce(age) {
console.log(`I'm ${this.name}, ${age} years old`);
}
const person = { name: 'Charlie' };
introduce.call(person, 30); // I'm Charlie, 30 years old
introduce.apply(person, [30]); // 同上
const boundFn = introduce.bind(person, 30);
boundFn(); // I'm Charlie, 30 years old
-
call和apply立即执行,区别只在参数传递方式(逗号 vs 数组) -
bind返回一个新函数,this 被永久绑定,后续调用无法覆盖 - 显式绑定优先级高于隐式绑定(如 obj.method())
构造函数与 class 方法中的 this
用 new 调用函数时,this 指向新创建的实例;class 中的方法默认绑定到实例(但需注意类字段箭头函数的写法)。
class Person {
constructor(name) {
this.name = name;
}
sayHi() {
console.log(`Hi, I'm ${this.name}`); // this 指向实例
}
// 箭头函数写法可避免 this 丢失(如传给 setTimeout)
delayedGreet = () => {
console.log(`Later: ${this.name}`);
};
}
- class 内部的普通方法(非箭头)本质仍是普通函数,靠调用方式决定 this
- 但 class 实例方法通常由实例调用(如
person.sayHi()),所以 this 天然指向实例 - 若将 class 方法赋值给变量再调用,仍可能丢失 this,建议用箭头函数字段或 bind 处理


















