TypeScript class decorator that modifies object instance

后端 未结 2 1661
暖寄归人
暖寄归人 2021-02-08 15:59

I\'m making a plugin for Aurelia and need a class decorator that

  1. adds attributes to the new object instance, and
  2. calls an external function with the new
2条回答
  •  深忆病人
    2021-02-08 16:26

    Here's a working version:

    function addAndCall(target: any) {
        var original = target;
    
        function construct(constructor, args) {
            var c: any = function () {
                this.newAttribute = "object instance value";
                ExternalModule.externalFunction(this);
                return constructor.apply(this, args);;
            }
    
            c.prototype = constructor.prototype;
            return new c();
        }
    
        var f: any = function (...args) {
            return construct(original, args);
        }
    
        f.prototype = original.prototype;
        return f;
    }
    

    (code in playground)

提交回复
热议问题