I’m trying to get prototypal inheritance working in the following way:
// Parent constructor
function Parent(obj) {
this.id = obj.id || 0;
this.name = obj.name || "";
};
// Child constructor
function Child(obj) {
Parent.call(this,obj);
this.type = obj.type || "";
}
Child.prototype = new Parent;
Seems textbook … but passing obj to both parent and child seems to be causing problems; Parent says obj is undefined when the child tries to prototype via Child.prototype = new Parent;. The only way I can get around this is with this ugly hack:
// 'Hacked' Parent constructor
function Parent(obj) {
if (obj) {
this.id = obj.id || 0;
this.name = obj.name || "";
}
};
Surely there’s a better way, but I can’t find an answer anywhere. Please help!!
Child.prototype = new Parent;creates a new Parent without any parameters and returns its prototype, assigning it toChild.prototype. This approach works well, but the problem is that it only works on parents with 0 parameters (new Parentis the equivalent ofnew Parent()in this context).For Parent constructors with parameters, I suggest defining an inherits function to handle your inheritance.
The fix I proposed earlier was that of
Child.prototype = Parent.prototype;. This will work, but nowChild.prototypeis a reference toParent.prototyperather than an object. In other words, if you add the method hello to the Child, then the Parent also receives that method. Bad times!The best solution to this problem is to define some
inheritsfunction as such:What we’re doing here is slightly different than just assigning
Parent.prototypeto the Child. We’re creating a new function which has the parent’s prototype and returning a new instance of the function F. So, when you add methods to the Child, you’re actually adding them to the prototype of theFfunction.To create the Child object now, you’d do:
You can then add methods to the Child without affecting the Parent.