JavaScript 中的 this 指向函数执行时的调用上下文对象,由调用方式决定:默认绑定(普通调用,非严格模式→全局对象,严格模式→undefined)、隐式绑定(obj.method()→obj)、显式绑定(call/apply/bind)、箭头函数(继承外层词法作用域的 this)。

JavaScript 中的 this 不指向函数本身,也不指向函数的词法作用域,它指向**函数执行时的调用上下文对象**——而这个对象由函数如何被调用决定,不是由函数如何被定义决定。
默认绑定:独立调用时 this 指向全局对象或 undefined
当函数以普通方式调用(非方法、非构造、非显式绑定),this 的值取决于是否启用严格模式:
function foo() {
console.log(this);
}
foo(); // 非严格模式 → window;严格模式 → undefined
⚠️ 常见陷阱:从对象方法中提取后单独调用,会触发默认绑定:
const obj = { name: 'Alice', say: () => console.log(this.name) };
const fn = obj.say;
fn(); // 箭头函数不适用 this 绑定规则,但普通函数会丢失 this
隐式绑定:点号调用时 this 指向调用它的对象
函数作为对象属性被调用(即 obj.method() 形式),this 指向该对象(obj)。
立即学习“Java免费学习笔记(深入)”;
- 只看「最后一次点号前的对象」:嵌套调用如
a.b.c.method(),this指向c - 隐式绑定会被更优先的绑定方式覆盖(如
call/apply、箭头函数、new)
const user = {
name: 'Bob',
greet() {
console.log(`Hello, ${this.name}`);
}
};
user.greet(); // Hello, Bob —— this 指向 user
⚠️ 注意:隐式绑定对「赋值后调用」无效:
const greet = user.greet; greet(); // Hello, undefined —— this 不再是 user
call / apply / bind:显式强制指定 this
这三个方法可手动控制 this 指向,优先级高于隐式绑定和默认绑定。
-
func.call(obj, arg1, arg2):立即执行,参数逐个传入 -
func.apply(obj, [arg1, arg2]):立即执行,参数以数组形式传入 -
func.bind(obj, arg1):返回新函数,this永久绑定为obj,后续调用不可更改
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
const bound = introduce.bind(person, 25);
bound(); // I'm Charlie, 25 years old
⚠️ bind 返回的函数无法再用 call 或 apply 改变 this(硬绑定);但箭头函数没有自己的 this,会沿作用域链向上找,不受任何显式绑定影响。
箭头函数:没有自己的 this,继承外层函数的 this
箭头函数不绑定 this,它直接捕获定义时所在词法作用域的 this 值,且该值不可被任何调用方式修改。
- 不能用
call/apply/bind改变其this - 不能作为构造函数使用(
new报错) - 适合用于回调(如
setTimeout、事件处理器),避免this丢失
const timer = {
value: 42,
start() {
setTimeout(() => {
console.log(this.value); // 42 —— this 继承自 start() 的调用上下文
}, 100);
}
};
timer.start();
如果这里用普通函数,this 就会指向 window 或 undefined,必须靠 bind 或中间变量保存。
真正容易出错的地方,往往不是记不住四条规则,而是混淆「定义位置」和「调用位置」——尤其是事件回调、定时器、异步 Promise 链、解构赋值后的函数调用。每次不确定时,直接在函数开头加 console.log(this),比查文档更快。











