views:

28

answers:

2

Hi,

I am trying inherit objects in JavaScript. Take a look at this example:

var BaseObject = function() {
};

var ChildObject = function() {
};

ChildObject.prototype.childMethod = function() {
};

ChildObject.prototype = new BaseObject();
ChildObject.prototype.constructor = ChildObject();

However, as soon as I do prototypal inheritance, the childMethod() disappears. What am I doing wrong here?

+2  A: 

You are overwriting the prototype when you assign it to BaseObject and BaseObject's prototype has no childMethod method.

To get the desired behavior you have to add childMethod after assigning the prototype to BaseObject:

var BaseObject = function() {
};

var ChildObject = function() {
};


ChildObject.prototype = new BaseObject();
ChildObject.prototype.constructor = ChildObject;
ChildObject.prototype.childMethod = function() {
    return 'childMethod';
};
c = new ChildObject();
alert(c.childMethod());
Vinko Vrsalovic
Ah, perfect. :)
rFactor
+1  A: 

Basically when you set create ChildObject

var ChildObject = function() {
};

ChildObject.prototype is pointing to a instance of Object, so when you add childMethod to prototype of ChildObject this method is added to that object.

But in this 2 lines you are replacing ChildObject prototype with new instance of BaseObject which does not know anything about childMethod

ChildObject.prototype = new BaseObject();
ChildObject.prototype.constructor = ChildObject();

Also I believe it should be

ChildObject.prototype.constructor = ChildObject;

So it creates circular reference.

miensol
The () were a typo, but still, what should I change to make this to work?
rFactor