TypeScript中直接用静态类方法作类装饰器时this为undefined如何解决
静态类方法作为类装饰器时this指向问题
我想把静态类方法用作类装饰器,但遇到了this指向的问题:直接使用静态方法时,方法内的this会变成undefined;用普通函数包装后可以正常运行,但我不想写这种冗余的包装。有没有办法让直接调用静态方法的写法正常工作?
示例代码
class Decorator { public static deco(constructor: new() => any) { console.log(this); return constructor; } } function anotherDeco(constructor: new() => any) { return Decorator.deco(constructor); } // 这里输出 `undefined`,不符合预期 @Decorator.deco class MyClass1 { } const instance1 = new MyClass1(); // 这里输出 `[class Decorator]`,符合预期 @anotherDeco class MyClass2 { } const instance2 = new MyClass2();
解决方案
问题出在装饰器调用时的函数绑定规则:当你把Decorator.deco作为装饰器传递时,它会被当作普通函数调用,而非类的静态方法调用,所以this会丢失(严格模式下默认是undefined)。
有两种简洁的解决方式:
1. 使用箭头函数作为静态属性
箭头函数的this是词法绑定的,会固定指向类本身:
class Decorator { public static deco = (constructor: new() => any) => { console.log(this); // 输出 [class Decorator] return constructor; }; } // 现在可以正常工作 @Decorator.deco class MyClass1 { }
2. 手动绑定this到类
在定义静态方法后,用bind把this绑定到Decorator类:
class Decorator { public static deco(constructor: new() => any) { console.log(this); // 输出 [class Decorator] return constructor; } } // 绑定this Decorator.deco = Decorator.deco.bind(Decorator); @Decorator.deco class MyClass1 { }
这两种方式都不需要额外的包装函数,就能让静态方法作为装饰器时this正确指向类本身。
内容的提问来源于stack exchange,提问作者jayatubi
相关产品推荐
相关产品推荐

