Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prototypal inheritance in JavaScript: I don't usually need calling the constructor of Parent object assigned to Child.prototype

I'm not new to JavaScript, but I never could understand a certain thing about its prototypal inheritance.

Say we have Parent and Child "classes" (functions Parent and Child that create objects). To be able to create Children, we first need to

Child.prototype = new Parent();

Here is the difficulty: by assigning the prototype to Child, we get one more object Parent that doesn't do anything in our code, just shares its properties with Children. But the constructor of Parent is still called! If parent represents, for example, a certain UI object, then in our application we will have one more such object which we actually didn't wish to create! And that, of course, may and will affect the state of our application.

I see a way to cope with this: to pass certain arguments to Parent constructor indicating that the object we are creating is just for prototype, not for general use, like:

RedButton.prototype = new Button(FOR_PROTO_ONLY);

and then in Parent constructor decide whether to do any displayable stuff or not. But this is such an ugly workaround!

In class-oriented languages, e.g. Java, we don't have such issue at all because inheriting doesn't suppose calling any additional functions. What should I do to not use such ugly techniques in my programs and still be able to create a nice-looking prototype hierarchy?

like image 880
gvlasov Avatar asked Nov 13 '22 23:11

gvlasov


1 Answers

One thing you can do is assign the instance of the parent to it's prototype property in the constructor. This means that you do not have to create an extraneous instance of the parent and therefore alleviates the issue you mentioned where you could end up with an extra GUI component being defined. However, it does mean that you must have at least one instance of the parent before instantiating an instance of the child and therefore this alone limits its usefulness to very specific circumstances.

Here's an example: 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();
like image 97
Greg Ross Avatar answered May 08 '23 19:05

Greg Ross