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?
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: