2016-12-30 45 views
4

我正在爲奧裏利亞一個插件,需要一個類裝飾器打字稿類裝飾修飾對象實例

  1. 增加屬性到新的對象實例,並
  2. 調用新對象的外部函數作爲論據。

我已經通過實例看,到目前爲止,我已經把(「僞十歲上下的」代碼)

return function addAndCall(target: any): any { 
    var original = target; 

    var newConstructor = function (...args) { 
     original.apply(this, args); 
     this.newAttribute = "object instance value"; 
     ExternalModule.externalFunction(this); 
    }; 

    newConstructor.prototype = Object.create(original.prototype); 
    newConstructor.prototype.constructor = original; 

    return <any>newConstructor; 
} 

  • 我不完全清楚的這裏的細節(或實際需要的)和
  • 它可能無法正常工作,因爲我使用此裝飾器從類實例化對象時發生Aurelia錯誤(並且我懷疑它是我的裝飾器而不是Aurelia框架是越野車)。

任何幫助和解釋將不勝感激!

回答

2

爲什麼不直接分配這些屬性的原型,隨後分配到該實例在第一次調用

// decorator 
function addAndCall(cb: Function, newField: string) { 
    // cb is now available in the decorator 
    return function(ctor: Function): void { 

    Object.defineProperty(ctor.prototype, newField, { 
     value: function(...args: any[]) { 
     return Object.defineProperty(this, newField, { 

      value: function(...args: any[]) { 
      console.log(newField, ...args); 
      } 

     })[newField](...args); 
     } 
    }); 
    cb(ctor); 
    } 
} 

let callMe = (decoratedCtor) => console.log(decoratedCtor); 
@addAndCall(callMe, 'propertyName') 
class AddToMe {} 

let addToMe = new AddToMe(); 
(<any>addToMe).propertyName(1, 2); 
+0

願望我早就看到了這個 - 花了我數小時纔想出來。 –

1

這裏有一個工作版本:

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