代码之家  ›  专栏  ›  技术社区  ›  JasonWyatt

像这样实例化dojo类有什么内在的危险吗?

  •  1
  • JasonWyatt  · 技术社区  · 16 年前

    extends implements 在Java中,但在运行时)。我提出了以下解决方案:

    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;

    如果有什么问题的话,这种类型的代码会出什么问题?(如何使它更健壮?)另外,在dojo中是否有我可能错过的东西可以让我更优雅地完成这项工作?

    1 回复  |  直到 16 年前
        1
  •  2
  •   Eugene Lazutkin    16 年前

    至少有两件事会出错:

    • 代码假定动态加载的模块与同步加载 dojo.require()
    • 使用以下命令实例化对象并复制其属性 dojo.mixin()
      • 它可能会覆盖某些内部(您保留 declaredClass ,但可能还有其他人)。
      • OOP帮助程序(如 this.inherited() )将为复制的方法断开。

    很难提出改进建议,因为不清楚您想要实现什么。如果要向对象添加平面混合,唯一需要确保对象是真正平面的。

    对代码的细微改进:

    • 宣告级 是在对象的原型上定义的,而不是在对象本身上定义的,您不需要保留它。只需将其从对象本身中删除:

      //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.safeMixin() ,跳过 constructor

    推荐文章