类构造器结合装饰器使用时this指向异常问题求助
问题分析与解决
这个问题我之前也踩过坑!核心原因是你在装饰器里错误地把方法绑定到了类的原型对象上,而不是实际创建的类实例上,导致this指向出错,最终this.thing变成了undefined。
原代码的问题拆解
你的装饰器里写了const func = descriptor.value.bind(target),这里的target其实是Foo类的原型对象(Foo.prototype),而不是new Foo('Hello world!')生成的实例。thing是类的私有实例属性,只会存在于每个具体的实例中,原型对象上根本没有这个属性,所以当你调用绑定后的func时,this指向原型,自然拿不到thing的值。
修复方案
我们只需要让装饰器里的方法在调用时,使用**当前实例的this**即可,不需要提前绑定到原型。修改装饰器的实现:
function someDecorator() { return (target: any, _2: any, descriptor: PropertyDescriptor) => { // 保存原始方法 const originalBar = descriptor.value; // 替换成普通函数(不要用箭头函数,否则this会继承外层上下文) descriptor.value = function() { console.log('Doing decorator stuff!'); // 用call把当前实例的this传给原始方法 originalBar.call(this); } } } class Foo { public constructor(private thing: string) { } @someDecorator() bar() { console.log(this.thing); } } new Foo('Hello world!').bar();
运行结果
现在执行代码会得到你期望的输出:
Doing decorator stuff!
Hello world!
补充说明
如果你的装饰器需要处理方法参数,也可以用apply代替call,比如originalBar.apply(this, arguments),这样能完整传递调用时的所有参数。
内容的提问来源于stack exchange,提问作者mortenl
相关产品推荐
相关产品推荐

