JavaScript prototype inheritance: I usually don't need to call the parent constructor assigned to Child.prototype

I'm not new to JavaScript, but I could never figure out a certain thing about its prototype inheritance.

Say we have parent and child classes (the Parent and Child functions that create objects). To be able to create children, we first need

Child.prototype = new Parent();

Here's the difficulty: by assigning a Child prototype, we get another Parent object that does nothing in our code, just shares its properties with Children. But the parent constructor is also called! If the parent represents, for example, a specific user interface object, then in our application we will have another such object that we really did not want to create! And this, of course, can affect the state of our application.

I see a way to handle this: pass certain arguments to the constructor of the parent, indicating that the object being created is intended only for the prototype, and not for general use, for example:

RedButton.prototype = new Button(FOR_PROTO_ONLY);

and then in the parent constructor decide whether to do any displayed things or not. But this is such an ugly workaround!

, , . Java, , - . , ?

+5
1

, , prototype . , , , , , GUI. , , , , , , .

: http://jsfiddle.net/xwwWZ/

var Child = function() {

    this.throwATantrum = function() {

        alert("Waaaaaaaaaah");

    }
};


var Parent = function() {

    // Set the prototype here to avoid having to create an extra instance elsewhere.
    Parent.prototype = this;

    this.sayHello = function() {

        alert("Hello!");

    }
};


// We must, however, instantiate an instance of the parent before we can
// instantiate an instance of a child.
var p = new Parent();


Child.prototype = Parent.prototype;

var c = new Child();

c.throwATantrum();
c.sayHello();
+1

All Articles