普通函数调用时this指向全局对象(非严格模式)或undefined(严格模式),易致“Cannot read property”错误;应优先用箭头函数、初始化绑定或call/apply临时绑定,避免bind滥用。

普通函数调用时 this 指向全局对象(非严格模式)或 undefined(严格模式)
这是最常被误判的场景。在全局作用域或普通函数中直接调用 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()会创建新函数,若在 render 中调用,可能触发不必要的重渲染(React)或内存开销
对象方法中 this 指向调用该方法的对象(但容易被“割裂”)
当写成 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)) - Vue 2 Options API 中,
methods会被自动绑定,但computed和watch的回调函数不会 —— 这里容易漏掉this绑定
class 中的 this 默认不自动绑定(尤其在事件监听和 setTimeout 中)
TypeScript 或 Babel 编译后的 class 并不改变 JavaScript 原生行为:类方法不是自动绑定的。哪怕写在 class A { handleClick() {} } 里,传给 addEventListener 或 setTimeout 后,this 依然会丢失。
立即学习“Java免费学习笔记(深入)”;
class Counter {
constructor() {
this.count = 0;
}
increment() {
this.count++; // this 是 undefined,报错
}
init() {
document.getElementById('btn').addEventListener('click', this.increment);
}
}
- 推荐做法:在 class 字段中用箭头函数定义方法(
increment = () => { this.count++; }),它天然绑定当前实例 - 不推荐:在
init()中每次调用都this.increment.bind(this)—— 每次新建函数,且若多次调用init(),会重复绑定 - 注意:React 函数组件 + Hooks 场景下,不存在
this,所以这个问题自然消失;但 class 组件仍需警惕
call / apply / bind 显式控制 this,但 bind 返回的是新函数
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 报错,先问一句:这个函数是在哪被调用的?是谁调用的?有没有中间变量承接?











