Is there a better way of having a class inherit prototype methods from another class and still be able to define new prototype methods on the class that inherits than this:
var ParentConstructor = function(){
};
ParentConstructor.prototype = {
test: function () {
console.log("Child");
}
};
var ChildConstructor = function(){
ParentConstructor.call(this)
};
ChildConstructor.prototype = {
test2: "child proto"
};
var TempConstructor = function(){};
TempConstructor.prototype = ParentConstructor.prototype;
ChildConstructor.prototype = new TempConstructor();
ChildConstructor.prototype.constructor = ChildConstructor;
var child = new ChildConstructor();
child.test();
console.log(child.test2)
console.log(child, new ParentConstructor());
Which isn't working, because I lose my test2
prototype method / property when I add the inheritance from my ParentConstructor
.
I've tried other ways to extend the prototype methods of a class with some prototype props form other classes but I have failed each time, because I couldn't find a way not to override the previous methods each time.
I have also tried the var Child = Object.create(Parent.Prototype)
, but when I define new props I lose the parent props.
Setting up inheritance should take place before you define new properties on the prototype of
ChildConstructor
. And when you define new prototype properties, you also shouldn't override the wholeprototype
property. Instead, you can simply add new properties, like you already did with theconstructor
property:The best example I can think of comes from:
http://robertnyman.com/2008/10/06/javascript-inheritance-how-and-why/
Note this example, has been updated, the first comment below is directed at the first code I had up, which contained the prototype inside the Robert method.