普通函数调用时this指向全局对象(非严格模式)或undefined(严格模式),易致“Cannot read property”错误;应优先用箭头函数、初始化绑定或call/apply临时绑定,避免bind滥用。
这是最常被误判的场景。在全局作用域或普通函数中直接调用 foo(),this 不指向函数自身,也不指向调用者,而是取决于执行上下文:
非严格模式下是 window(浏览器)或 global(Node.js);严格模式下就是 undefined。
常见错误现象:在事件回调、定时器或异步回调里访问 this.name 报 Cannot read property 'name' of undefined。
.bind(this)、箭头函数(继承外层 this)、或把方法提前绑定到对象上(如构造函数中 this.handleClick = this.handleClick.bind(this))this,它会沿作用域链向上找,所以不能用在需要动态 this 的场景(比如 Vue 或 React 类组件的生命周期钩子中需访问实例,但箭头函数写法会导致 this 绑定失效).bind()
当写成 obj.method() 时,this 是 obj;但一旦把方法单独提取出来,比如 const fn = obj.method; fn();,就退化为上一条的普通函数调用,this 失控。
const obj = {
name: 'Alice',
sayName() {
console.log(this.name); // 正常输出 'Alice'
}
};
const say = obj.sayName;
say(); // undefined(严格模式)或报错
sayName = () => console.log(this.name));② 在构造/初始化阶段绑定(this.sayName = this.sayName.bind(this));③ 调用时临时绑定(say.call(obj) 或 say.apply(obj))methods 会被自动绑定,但 computed 和 watch 的回调函数不会 —— 这里容易漏掉 this 绑定TypeScript 或 Babel 编译后的 class 并不改变 JavaScript 原生行为:类方法不是自动绑定的。哪怕写在 class A { handleClick() {} } 里,传给 addEventListener 或 setTimeout 后,this 依然会丢失。
class Counter {
constructor() {
this.count = 0;
}
increment() {
this.count++; // this 是 undefined,报错
}
init() {
document.getElementById('btn').addEventListener('click', this.increment);
}
}
increment = () => { this.count++; }),它天然绑定当前实例init() 中每次调用都 this.increment.bind(this) —— 每次新建函数,且若多次调用 init(),会重复绑定this,所以这个问题自然消失;但 class 组件仍需警惕call 和 apply 是立即执行,bind 是预设参数并返回一个新函数。很多人混淆三者行为,尤其在事件系统中误用 bind 导致重复绑定或内存泄漏。
fn.call(obj, a, b) → 立即以 obj 为 this 执行,参数逐个传入fn.apply(obj, [a, b]) → 同上,但参数以数组形式传入const boundFn = fn.bind(obj, a) → 返回新函数,后续调用时 this 固定为 obj,且第一个参数永远是 a
bind 不会覆盖前一次绑定 —— fn.bind(obj1).bind(obj2),最终 this 仍是 obj1;bind 无法被后续的 call 覆盖(除非原函数本身用了 Reflect.apply 等底层机制)this 报错,先问一句:这个函数是在哪被调用的?是谁调用的?有没有中间变量承接?