Search code examples
javascriptbackbone.js

How to create instance of object from prototype method


Is it possible to create an instance of an object from it's prototype if the prototype is being used for multiple sublclasses?

For example, if I have:

var BaseClass = Backbone.Model.extend({
   createNewForMap: function(map) {
     // Here I would like to create a new instance of the
     // class that the method is being called for.
   }
});

var ClassOne = BaseClass.extend({});
var ClassTwo = BaseClass.extend({});

Then, somewhere in my application code, I want to be able to call:

var model = ClassOne.createNewForMap(map);

or

var model = ClassTwo.createNewForMap(map);

And have model be an instance of ClassOne or ClassTwo.


Solution

  • It is possible to define a static method on the BaseClass, that will serve as a factory function for it or any children classes, that inherit it.

    Backbone.Model.extend allows you to specify so-called classProperties, that might be considered as something similair to static methods from conservative OOP programming.

    var BaseClass = Backbone.Model.extend({}, {
      
      // A static method for invoking constructor function.
      createNewForMap: function(map) {
        return new this;
      }
    });
    
    var ClassOne = BaseClass.extend({
      initialize: function() { this.foo = 'bar' }
    });
    
    var ClassTwo = BaseClass.extend({
      initialize: function() { this.foo = 'buz' }
    });
    
    console.log(ClassTwo.createNewForMap().foo); // buz
    <script src="//underscorejs.org/underscore-min.js"></script>
    <script src="//backbonejs.org/backbone-min.js"></script>