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 to Child.prototype. This approach works well, but the problem is that it only works on parents with 0 parameters (new Parent is the equivalent of new 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 now Child.prototype is a reference to Parent.prototype rather 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 inherits function as such:
function inherit(parentPrototype) {
function F() {};
F.prototype = parentPrototype;
return new F;
}
What we're doing here is slightly different than just assigning Parent.prototype to 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 the F function.
To create the Child object now, you'd do:
function Child() {};
Child.prototype = inherit(Parent.prototype); // returns an instance of F
You can then add methods to the Child without affecting the Parent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With