谈谈你对 this 的理解
参考答案
this 是函数执行时的上下文对象,其值取决于调用方式(箭头函数除外,取词法作用域)。
绑定规则(优先级从高到低)
- new 绑定:
new F()→ this 是新实例; - 显式绑定:
call/apply/bind指定; - 隐式绑定:
obj.fn()→ this 是 obj(const f = obj.fn; f()则丢失); - 默认绑定:普通调用 → 非严格模式为全局对象(window/globalThis),严格模式为
undefined。 - 箭头函数:不适用上述规则,取定义处外层 this,且无法改变。
特例
- 事件处理函数中 this 为绑定的元素;
setTimeout回调中 this 为全局/undefined;- class 方法脱离实例调用会丢 this(用箭头字段或 bind 解决);
- 严格模式与
'use strict'影响默认绑定。
判断口诀:看"谁调用的",而不是"在哪定义的"。