Drew Christensen
Drew Christensen

Reputation: 145

Constructors Which Create Constructors (JavaScript)

In a simulation I'm making, I'll have an Element class, which I'll call with params about the properties of that Element (melting and boiling temperatures, rules for reactions with other Elements, color, density, etc.) to create the basic types of Elements (water, oxygen, carbon, etc.). From these, I simply would like to create new "Atoms" from the water, oxygen, and carbon templates I would have. I'm wondering if there's a way to use a constructor (Element) to create a new constructor (like Water)? For example, I would like to be able to do something like this.

var Element = function(/* params */) {
    // common element properties and basic functions
}
var Water = new Element(); // create the new element
var WaterAtom = new Water(); // create the atom (an instance of the element)
// draw the atom, manipulate it, react with other atoms, etc.

I'm basically asking, can a constructor create another constructor? I would like it this way so I don't have to create tons and tons of .prototype code that extends the basic Element class.

Upvotes: 0

Views: 66

Answers (2)

SimpleJ
SimpleJ

Reputation: 14758

You could just write a utility function for generating subclasses of Element:

function Element() {}

function subElement() {
  function SubElement() {}
  SubElement.prototype = Object.create(Element.prototype);
  return SubElement;
}

var Water = subElement();
var waterAtom = new Water();

Upvotes: 1

Bergi
Bergi

Reputation: 664185

I think what you are looking for is

function Element(…) {
    // init properties that all elements share
}
Element.prototype.… = function(…) { … }; // add all methods of elements

Element.makeType = function(rules) {
    function ElementType(…) {
        Element.call(this, …);
    }
    ElementType.prototype = Object.create(Element.prototype);
    ElementType.prototype.constructor = ElementType;
    ElementType.prototype.rules = rules;
    return ElementType;
};

so that you can use it like

var Water = Element.makeType(function(…) {
    // do whatever makes water special
});

var drop = new Water(…);

Upvotes: 1

Related Questions