访问器装饰器和实例类上下文

时间:2017-01-17 11:52:09

标签: javascript typescript decorator

我无法弄清楚如何在类访问器装饰器中绑定实例化的类上下文。简而言之,我的课程是:

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

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

2 个答案:

答案 0 :(得分:2)

这不是TypeScript问题,如果没有this,请致电oldSet(),从而导致this上下文丢失。

受过教育的猜测:尝试oldSet.call(this, value)

答案 1 :(得分:2)

嗯,毕竟我自己发现了这个问题..显然,你不能在描述符覆盖中使用箭头语法。所以,这可以按预期工作(也感谢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);
    }
}