普通函数独立调用时,this指向全局对象(非严格模式)或undefined(严格模式);箭头函数无this,继承外层作用域;事件处理器中this默认指向绑定元素,类方法作事件处理器易丢失this;call/apply立即执行并绑定this,bind返回预设this的新函数。
this 指向全局对象(非严格模式)或 undefined(严格模式)这是最常踩坑的场景。函数独立调用(如 foo()),不通过对象属性或事件绑定等方式触发,this 就不会自动绑定到预期对象。
this 指向 window;严格模式下是 undefined,调用 this.xxx 会直接报错 Cannot read property 'xxx' of undefined
global(非严格)或 undefined(严格)this,它继承外层函数作用域的 this 值,因此不受调用方式影响function sayName() {
console.log(this.name);
}
const obj = { name: 'Alice' };
sayName(); // undefined(严格模式)或 window.name(非严格)
// 修复方式之一:显式绑定
sayName.call(obj); // 'Alice'
sayName.apply(obj); // 'Alice'
sayName.bind(obj)(); // 'Alice'
this 默认指向触发事件的 DOM 元素给元素绑定事件时(如 btn.addEventListener('click', handler)),浏览器会把 this 设为当前 Event.currentTarget,也就是绑定监听器的那个元素。
this 不再指向 DOM 元素,而是外层作用域的 this(通常是 window 或模块顶层)event.target 获取实际点击的元素(可能和 this 不同,比如子元素冒泡触发)this —— 因为传入的是函数引用,不是调用class ButtonController {
constructor(el) {
this.el = el;
this.count = 0;
// ❌ 错误:this 指向 el,不是 ButtonController 实例
el.addEventListener('click', this.handleClick);
}
handleClick() {
this.count++; // TypeError: Cannot set property 'count' of undefined
}
}
// ✅ 正确写法(任选其一):
// 1. bind 在构造时
el.addEventListener('click', this.handleClick.bind(this));
// 2. 使用箭头函数(推荐)
el.addEventListener('click', () => this.handleClick());
// 3. 在 class 字段中定义箭头方法
handleClick = () => { this.count++; };
call、apply、bind 的区别与适用场景三者都用于手动控制 this 绑定,但调用时机和参数传递方式不同。
fn.call(obj, arg1, arg2):立即执行,参数逐个列出fn.apply(obj, [arg1, arg2]):立即执行,参数以数组形式传入fn.bind(obj, arg1, arg2):返回新函数,不立即执行;后续调用时 this 固定为 obj,且预设部分参数(柯里化)bind 返回的函数无法再用 call/apply 覆盖 this(硬绑定优先级最高)function logInfo(prefix) {
console.log(`${prefix}: ${this.value}`);
}
const data = { value: 42 };
logInfo.call(data, '[CALL]'); // '[CALL]: 42'
logInfo.apply(data, ['[APPLY]']); // '[APPLY]: 42'
const bound = logInfo.bind(data, '[BIND]');
bound(); // '[BIND]: 42'
this 丢失 —— 本质是函数赋值问题当写 const fn = obj.method,
就断开了方法与原对象的关联。此时 fn() 是普通调用,this 不再是 obj。
this.handleClick 给子组件、或定时器回调:setTimeout(obj.method, 100)
const { method } = obj; method();
.bind、箭头函数包装,或在调用处用 obj.method() 形式(而非提前提取)const obj = {
name: 'Bob',
greet() { console.log(`Hello, ${this.name}`); }
};
const greet = obj.greet;
greet(); // 'Hello, undefined'
// ✅ 安全做法:
obj.greet(); // 直接调用
greet.call(obj); // 显式绑定
const safeGreet = () => obj.greet(); // 包装成箭头函数
真正容易忽略的不是“怎么绑”,而是**什么时候已经悄悄解绑了**——比如把方法传进第三方库、作为 Promise 回调、放进数组然后 forEach 执行,这些看似无害的操作,都会让 this 脱离原始上下文。