0

Inside a namespace, i have two object definitions (AKA: "classes").

¿How can I make one class inherit from another inside the namespace?

First, I tried with this:

var ns = { // the namespace
    OneClass : function() { 
        console.log("Instance of OneClass has been constructed");
        this.foo = ":)";
    },

    Inherited : function() {
        this.anotherFoo = "):";
    },

    Inherited.prototype : new this.OneClass,
    Inherited.prototype.constructor = this.Inherited
};

but this gives an error on the 11th line: SyntaxError: missing : after property id

So I changed the code to this, and it worked:

var ns = { // the namespace
    OneClass : function() { 
        console.log("Instance of OneClass has been constructed");
        this.foo = ":)";
    }

    Inherited : function() {
        this.anotherFoo = "):";
    }
};

ns.Inherited.prototype = new ns.OneClass();
ns.Inherited.prototype.constructor = ns.Inherited;

anyway, I don't like this solution, because the inheritance declaration must be declared at the end of the namespace, this makes the code "messy".

So I'd rather to have the inheritance declaration as close as possible from the Inherited object definition.

0 Answers0