【问题标题】:Creating a property getter and setter with TypeScript Decorator使用 TypeScript 装饰器创建属性 getter 和 setter
【发布时间】:2018-04-17 12:09:20
【问题描述】:

我想用 TypeScript Decorator 创建一个属性 getter 和 setter,但我坚持定义在更改或请求属性时要运行的函数。

如果我的Field.watch 装饰器有以下用法:

export class Test {
   ...
   @Field.watch({onSet: this.resetCssCache})
   public layoutId = 0;
   ...
   public resetCssCache() {
      ...
   }
   ...
}

装饰器的实现是:

export class Field {

    public static watch(watchers: { onGet?: () => any, onSet?: (newValue: any, oldValue: any) => any }): Function {
        return (target: any, key: string) => {

            // property getter
            const getter = function() {
                return this['_' + key];
            };

            // property setter
            const setter = function(newVal) {
                if (watchers.onSet) {
                    this['_' + key] = watchers.onSet(newVal, this['_' + key]);
                }
                this['_' + key] = newVal;
            };

            // Delete property.
            if (delete this[key]) {

                // Create new property with getter and setter
                Object.defineProperty(target, key, {
                    get: getter,
                    set: setter,
                    enumerable: true,
                    configurable: true
                });
            }
        }
    }
}

我在@Field.watch({onSet: this.resetCssCache}) 上收到一个错误,告诉我this 没有定义。

我猜装饰器是在定义级别而不是实例级别上解释的。 有没有办法将非静态方法绑定到我的装饰器的 onSet 属性?

【问题讨论】:

    标签: typescript decorator


    【解决方案1】:

    您对“this”代表什么的假设是不正确的。正如您在问题的最后一句中指出的那样,您似乎正在寻找实例级别的装饰器。

    我过去也有类似的需求,这个issue 提供了答案。

    这个issue也提供了解决方案。

    祝你好运! ;-)

    【讨论】:

      【解决方案2】:

      你不能在装饰器中通过this访问方法,你可以使用prototype传递方法:

      export class Test {
      
          @Field.watch({onSet: Test.prototype.resetCssCache })
          public layoutId = 0;
      
          public resetCssCache() {
      
          }
      
      }
      

      请注意,这意味着当您调用watchers.onSet(newVal, this['_' + key]); 时,resetCssCache 中的this 实际上将是watchers,而不是Test 的实例。您应该使用call 调用它,这样您就可以显式传递this watchers.onSet.call(this, newVal, this['_' + key])

      【讨论】:

      • 这正是我需要的!非常感谢!
      • 我可以通过装饰器中的目标访问原型,这是 typescript (v2.9) 中的新功能吗?
      猜你喜欢
      • 2017-11-28
      • 2010-11-16
      • 1970-01-01
      • 2021-11-04
      • 1970-01-01
      • 1970-01-01
      • 2018-05-02
      • 2019-07-29
      • 2015-04-25
      相关资源
      最近更新 更多