2009-11-16 27 views
1

我需要能夠在運行時在Dojo中實例化類的對象,並將其混合到另一個對象中(有點像在Java中指定extendsimplements,但是在運行時)。我想出了以下解決方案:像這樣實例化dojo類有什麼內在的危險嗎?

var declaredClassBackup = this.declaredClass; // backup the "declaredClass" 

var mixinObject = null; 
try { 
    dojo.require(kwArgs.mixinClassName); 

    /* 
    * Eval the mixinClassName variable to get the Function reference, 
    * then call it as a constructor with our mixinSettings 
    */ 
    mixinObject = new (eval(kwArgs.mixinClassName))(kwArgs.mixinSettings); 
} catch (e){ 
    if(console){ 
     console.error("%s could not be loaded as a mixin.", 
       kwArgs.mixinClassName); 
    } 
    mixinObject = new package.path.DefaultMixin(kwArgs.mixinSettings); 
} 
dojo.mixin(this, mixinObject); 

/* 
* Re-set the declaredClass name back to that of this class. 
*/ 
this.declaredClass = declaredClassBackup;

這種類型的代碼有什麼問題,如果有的話? (你會如何使它更強大?)另外,有沒有什麼我可以錯過的道場,這會爲我更優雅地做到這一點?

+0

什麼定義'kwArgs.mixinClassName'? – 2009-11-16 18:38:01

+0

kwArgs是傳遞給包含上述代碼的函數的對象...該函數的調用者是誰定義kwArgs.mixinClassName的值 – JasonWyatt 2009-11-16 18:49:19

回答

2

至少有兩件事情可以去錯了:

  • 你的代碼假定一個動態加載模塊與dojo.require()同步加載。只適用於默認加載程序。 XD加載器將異步加載事物,破壞你的邏輯。
  • 一個對象被實例化並使用dojo.mixin()複製了它的屬性,它必然會使它變平。這意味着:
    • 它可能會覆蓋一些內部(您保留declaredClass,但可能有其他人)。
    • 對於複製的方法,OOP幫助程序(如this.inherited())將被中斷。

但是,如果這些限制符合你的使用情況,你應該罰款。

很難提出改進建議,因爲它不清楚你想達到什麼目的。如果你想添加平面混合到一個對象,唯一需要確保對象是真正平坦的。

輕微改善你的代碼:

  • declaredClass被定義在對象的原型,而不是對象本身⇒你並不需要保存它。剛剛從對象本身刪除:

    //var declaredClassBackup = this.declaredClass; // backup the "declaredClass" 
    // no need 
    // the rest of your code 
    ... 
    /* 
    * Re-set the declaredClass name back to that of this class. 
    */ 
    //this.declaredClass = declaredClassBackup; 
    // no need 
    delete this.declaredClass; 
    
  • 相反的dojo.mixin()可以使用dojo.safeMixin(),它跳過constructor和裝飾方法。此方法自Dojo 1.4(包括當前中繼)可用。