访问装饰器和实例化 class 上下文

Accessor decorator and instanced class context

我不知道如何在 class 访问器装饰器中绑定实例化的 class 上下文。我的 class 简而言之是:

class A {
    protected persistProperty(a, b) {
        // ...
    }
}

class C extends A {
    @validatorTest
    public set coolStuff(email: string) {
        this.persistProperty('company.email', email);
    }
}

装饰师:

function validatorTest(
    target: any,
    propertyKey: string,
    descriptor: TypedPropertyDescriptor<string>
) {
    const oldSet = descriptor.set;

    descriptor.set = (value: string) => {
        if (value && !value.match(...)) {
            throw new Error();
        }

        oldSet(value);
    }
}

现在使用访问器时出现问题:

let foo = new C();

c.coolStuff = 'a@b.c';

我收到以下错误:

TypeError: Cannot read property 'persistProperty' of undefined

所以,正如我提到的,实例化的上下文 class 似乎没有绑定到装饰器。我在这里做错了什么?

这不是 TypeScript 问题,您在没有 this.

的情况下调用 oldSet() 丢失了 this 上下文

有根据的猜测:尝试oldSet.call(this, value)

好吧,毕竟我自己发现了问题.. 显然,您不能在描述符覆盖中使用箭头语法。因此,这按预期工作(也感谢 Madara 的回答):

function validatorTest(
    target: any,
    propertyKey: string,
    descriptor: TypedPropertyDescriptor<string>
) {
    const oldSet = descriptor.set;

    descriptor.set = function(value: string) {
        if (value && !value.match(...)) {
            throw new Error();
        }

        oldSet.call(this, value);
    }
}