哪些原因会导致js里this指向混乱?
参考答案
- 调用方式不同:
obj.fn()指向 obj,const f = obj.fn; f()指向 undefined/global; - 回调丢失上下文:setTimeout、事件监听、数组方法传方法引用;
- 解构/赋值:
const { fn } = obj; fn()丢 this; - 箭头函数误用:需要动态 this 的地方用了箭头函数,绑定到外层;
- call/apply/bind 使用不当 或 bind 后又 new;
- 严格模式差异:非严格模式普通调用 this 是 window,严格模式是 undefined;
- 构造函数与 return 对象:new 时返回对象会替换实例;
- 嵌套函数内层:内层普通函数的 this 不是外层的 this。
解决:优先箭头函数保留外层、显式 bind、或把方法写成独立纯函数 + 传参。