JavaScript中this指向取决于调用方式而非定义方式:谁调用函数,this就指向谁(箭头函数除外,它继承外层this)。

JavaScript 中 this 的指向不是看函数怎么定义的,而是看它**怎么被调用的**。核心规则只有一条:谁调用函数,this 就指向谁(箭头函数除外,它不绑定自己的 this,而是继承外层作用域的)。下面分常见场景说明。
普通函数直接调用(非严格模式 vs 严格模式)
在全局作用域下直接写 fn() 调用函数:
对象方法调用(最典型场景)
当函数作为对象的属性被调用时,this 指向该对象:
const obj = {
name: 'Alice',
say() {
console.log(this.name); // 'Alice'
}
};
obj.say(); // this → obj
⚠️ 注意:一旦把方法单独提取出来,就丢失了绑定关系:
立即学习“Java免费学习笔记(深入)”;
const fn = obj.say; fn(); // this → window(非严格)或 undefined(严格)
call / apply / bind 显式绑定
这三个方法可以手动指定 this 值:
-
fn.call(obj, arg1, arg2)—— 立即执行,this 为 obj -
fn.apply(obj, [arg1, arg2])—— 同上,参数以数组传入 -
const boundFn = fn.bind(obj)—— 返回新函数,this 永远绑定为 obj
bind 绑定后无法被后续 call/apply 覆盖(除非 new 调用)。
构造函数调用(new 关键字)
用 new Fn() 调用时,this 指向新创建的实例对象:
function Person(name) {
this.name = name; // this → 新生成的实例
}
const p = new Person('Bob');
此时即使函数内部有 call/apply,也不会影响 new 的 this 绑定(new 优先级最高)。
箭头函数(无独立 this)
箭头函数不绑定自己的 this,它会沿作用域链向上查找,使用外层普通函数或全局作用域的 this 值:
const obj = {
name: 'Charlie',
regular() {
console.log(this.name); // 'Charlie'
const arrow = () => console.log(this.name); // 也输出 'Charlie'
arrow();
}
};
因此箭头函数不能用作构造函数(不能 new),也不支持 call/apply/bind 改变 this。
事件处理函数中的 this
DOM 事件监听器中,回调函数的 this 默认指向触发事件的元素(即 event.currentTarget):
button.addEventListener('click', function() {
console.log(this === button); // true
});
但如果用箭头函数,则 this 指向外层作用域,不再是 button:
button.addEventListener('click', () => {
console.log(this === button); // false(通常是 window 或 undefined)
});
定时器与异步回调
setTimeout / setInterval 的回调函数属于普通函数调用,this 默认指向全局对象(非严格)或 undefined(严格):
const obj = {
name: 'David',
init() {
setTimeout(function() {
console.log(this.name); // undefined(严格模式)
}, 100);
// ✅ 正确做法:用箭头函数,或 bind,或存 this
setTimeout(() => console.log(this.name), 100); // 'David'
}
};
理解 this 的关键在于观察**调用位置和调用方式**,而不是函数定义的位置。多练习几种调用形式,再结合优先级(new > 显式绑定 > 对象方法 > 普通调用),基本就能准确判断了。











