【问题标题】:Implement TS/JS decorator using private instance method?使用私有实例方法实现 TS/JS 装饰器?
【发布时间】:2016-01-23 14:27:57
【问题描述】:

是否可以使用私有方法来实现装饰器?例如

class Person {
    @validateSomethingFirst
    public doSomething() {
    }

    private validateSomethingFirst() { ... }
}

我的初步调查似乎表明这是不可能的,但我似乎找不到可靠的参考。

【问题讨论】:

  • 我问的是私有 decorators,而不是 functions。谢谢!

标签: javascript typescript decorator


【解决方案1】:

是的,如果您将私有方法声明为静态是可能的:

class AAA
{
    private static Dec(target: any, key: string) 
    {
        console.log("Decorator applied");
    }

    @AAA.Dec  
    public Prop: number;    
}

使用实例方法是不可能的,因为要引用私有实例方法,您需要访问当时未定义的“this”。通过查看生成的 js 代码很容易知道原因。如果我们在上面的示例中更改为实例方法 - js 代码将是:

var AAA = (function () {
    function AAA() {
    }
    AAA.Dec = function (target, key) {
        console.log("Decorator applied");
    };
    __decorate([
        this.Dec, 
        __metadata('design:type', Number)
    ], AAA.prototype, "Prop", void 0);
    return AAA;
})();

这里的“this”在调用时是未定义的。

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2019-01-03
    • 2019-02-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多