【问题标题】:Accessor decorator and instanced class context访问器装饰器和实例化类上下文
【发布时间】:2017-01-17 11:52:08
【问题描述】:

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

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

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

【问题讨论】:

    标签: javascript typescript decorator


    【解决方案1】:

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

    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);
        }
    }
    

    【讨论】:

      【解决方案2】:

      这不是 TypeScript 问题,在没有 this 的情况下调用 oldSet(),您已经丢失了 this 上下文。

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

      【讨论】:

      • @madara,在这个例子中,有没有一种简单的方法来转发参数。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-26
      • 1970-01-01
      • 2013-02-18
      • 2011-01-22
      • 1970-01-01
      • 1970-01-01
      • 2018-04-28
      相关资源
      最近更新 更多