Search code examples
javascriptinheritanceprototype-programming

JavaScript prototypal inheritance workaround


Here is an example:

var Box = function() {
    this.id = generateUniqueId();
};
Box.prototype = {
    add:function(parent) {
        parent.appendChild(this.elm);
    }
};

var NewBox = function() {
    this.newThing = true;
};
NewBox.prototype = new Box();
NewBox.prototype.remove = function() {
    this.elm.parentNode.removeChild(this.elm);
};

var a = new NewBox();
var b = new NewBox();
alert(a.id); // alerts 0
alert(b.id); // also alerts 0! :@

I would like to have a and b (basically each time I create a NewBox) have their own id. I understand that NewBox is using prototypal inheritance and is thus inheriting from a single instance of the generated id that it gets from Box, but I would like it so that each NewBox gets its own id without having to explicitly say that inside the NewBox constructor.

Maybe it's impossible or I'm doing something really wrong, so please help!

Thanks a lot!


Solution

  • Maybe it's impossible or I'm doing something really wrong, so please help!

    You're doing something wrong.

    If you want instance-specific values, initialize them in the constructor, not the prototype.