Search code examples
javascriptinheritanceprototypejsprototypeinstance

prototype.js instance property from mixins


I am looking for a way to create objects in javascript using multiple inheritance, in such way to have methods on the prototype and relevant properties on the instance, all defined in the same class. This is how far I was able to get with 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(){...}
});

I would like the elements array to be declared in the mixin together with corresponding methods, but it must not be shared between instances of Page. I tried making HasElementsMixin into another base class, but it doesn't work. I would like to avoid having to do MyBaseClass -> HasElements -> Page

Is it possible with prototype.js, or maybe I should be using another library or native solution?


Solution

  • You can give your mixin a "constructor" as well. It needs to be called from every class that implements the mixin, just like you need to call $super in subclasses:

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