有关实例化这样的dojo类有什么本质上的危险吗?

时间:2009-11-16 17:55:33

标签: javascript reflection error-handling dojo cross-browser

我需要能够在运行时在Dojo中实例化一个类的对象并将其混合到另一个对象中(有点像在Java中指定extendsimplements,但在运行时) 。我提出了以下解决方案:

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;

这类代码有什么问题,如果有的话? (你怎么能让它变得更强大呢?)另外,有什么东西我可能只是在道场中错过了会更优雅地为我做这件事吗?

1 个答案:

答案 0 :(得分: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(包括当前主干)以来,此方法可用。