强制类作用域中的方法在预期范围内调用。
类方法作为独立变量传递时,不会保留类作用域,“this”不再指代当前类。解决方法是定义为“this: void”或者使用箭头函数。
class MyClass {
public logUnbound(): void {
this.logUnbound();
}
public logBound = () => {
this.logUnbound();
};
}
const instance = new MyClass();
// logBound will always be bound with the correct scope
const logBound = instance.logBound;
logBound();