JavaScript - Inheritance in Constructors

Posted by j0ker on Stack Overflow See other posts from Stack Overflow or by j0ker
Published on 2012-06-25T14:38:22Z Indexed on 2012/06/25 15:16 UTC
Read the original article Hit count: 164

Filed under:
|

For a JavaScript project we want to introduce object inheritance to decrease code duplication. However, I cannot quite get it working the way I want and need some help.

We use the module pattern. Suppose there is a super element:

a.namespace('a.elements.Element');
a.elements.Element = (function() {
    // public API -- constructor
    Element = function(properties) {
        this.id = properties.id;
    };

    // public API -- prototype
    Element.prototype = {
        getID: function() {
            return this.id;
        }
    };

    return Element;
}());

And an element inheriting from this super element:

a.namespace('a.elements.SubElement');
a.elements.SubElement = (function() {
    // public API -- constructor
    SubElement = function(properties) {
        // inheritance happens here
        // ???
        this.color = properties.color;
        this.bogus = this.id + 1;
    };

    // public API -- prototype
    SubElement.prototype = {
        getColor: function() {
            return this.color;
        }
    };

    return SubElement;
}());

You will notice that I'm not quite sure how to implement the inheritance itself. In the constructor I have to be able to pass the parameter to the super object constructor and create a super element that is then used to create the inherited one. I need a (comfortable) possibility to access the properties of the super object within the constructor of the new object. Ideally I could operate on the super object as if it was part of the new object.

I also want to be able to create a new SubElement and call getID() on it.

What I want to accomplish seems like the traditional class based inheritance. However, I'd like to do it using prototypal inheritance since that's the JavaScript way. Is that even doable?

Thanks in advance!

EDIT: Fixed usage of private variables as suggested in the comments. EDIT2: Another change of the code: It's important that id is accessible from the constructor of SubElement.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about inheritance