箭头函数在 class 方法中能用吗
可以用,但必须作为实例属性赋值使用。将 method = () => {} 写在类体中,它会在每次创建实例时执行,把箭头函数绑定到当前实例上,从而自动获得正确的 this 引用。

为什么普通方法需要手动绑定 this
因为普通方法默认不绑定 this,调用方式决定其指向。如果直接传递方法引用而不绑定,this 会丢失或指向全局对象,导致报错。

使用 Husky 将 pre-commit、pre-push 和 commit-msg 检查集成到仓库中,以便代理和开发人员在更改离开工作站之前运行相同的本地防护措施。
class NormalClass {
constructor() {
this.value = 42;
}
getValue() {
return this.value;
}
}
const instance = new NormalClass();
console.log(instance.getValue()); // 42
// 模拟丢失上下文
const looseMethod = instance.getValue;
console.log(looseMethod()); // undefined (严格模式下报错)箭头函数如何自动处理 this
箭头函数没有自己的 this,它会捕获定义时的词法作用域。在类属性中使用箭头函数,定义时 this 就是实例本身,因此无需任何额外绑定操作即可安全使用。
立即学习“Java免费学习笔记(深入)”;

class ArrowClass {
constructor() {
this.value = 42;
this.getValue = () => this.value;
}
}
const instance = new ArrowClass();
console.log(instance.getValue()); // 42
// 即使丢失上下文也能正常工作
const looseMethod = instance.getValue;
console.log(looseMethod()); // 42

















