【问题标题】:prototype.js instance property from mixins来自 mixins 的prototype.js 实例属性
【发布时间】:2014-09-16 19:36:06
【问题描述】:

我正在寻找一种使用多重继承在 javascript 中创建对象的方法,这样可以在原型上拥有方法,在实例上拥有相关属性,所有这些都定义在同一个类中。这就是我使用prototype.js 所能达到的程度:

var MyBaseClass = Object.create({
  initialize: function(){
    this.id = ID_Generator.getNextID();
  }
});

var HasElementsMixin = {
  addElement: function(){...},
  removeElement: function(){...}
}

var Page = Class.create(MyBaseClass, HasElementsMixin, {
  initialize: function($super){
    $super();
    this.elements = [];
  },
  render: function(){...}
});

我希望在 mixin 中声明 elements 数组以及相应的方法,但它不能在 Page 的实例之间共享。我尝试将 HasElementsMixin 制作成另一个基类,但它不起作用。我想避免做 MyBaseClass -> HasElements -> Page

prototype.js 是否可行,或者我应该使用其他库或本机解决方案?

【问题讨论】:

    标签: javascript inheritance prototypejs prototype instance


    【解决方案1】:

    你也可以给你的 mixin 一个“构造函数”。它需要从每个实现 mixin 的类中调用,就像您需要在子类中调用 $super 一样:

    var HasElementsMixin = {
      initializeElements: function() {
        this.elements = [];
      },
      addElement: function(){…},
      removeElement: function(){…}
    };
    
    var Page = Class.create(MyBaseClass, HasElementsMixin, {
      initialize: function($super){
        $super();
        this.initializeElements();
      },
      render: function(){…}
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-06
      • 2017-06-14
      • 1970-01-01
      • 2012-03-01
      • 2011-02-21
      • 1970-01-01
      相关资源
      最近更新 更多