In javascript, there is unfortunately no clean way to pass arguments up the constructor chain because constructors inherit from objects, not other constructors. For example consider the following:
function Person (name) {
this.name = name;
}
function Accountant () {}
Accountant.prototype = new Person('');
Now, if you want to create an Accountant
there's no clean way to give him a name:
var x = new Accountant();
Of course, in this simple example you can simply set his name manually after creating him:
x.name = 'Andy';
But real world code may not always be as easily worked-around. Some object keep state in closures which means you'll have no way to pass the argument back to the parent's constructor because you've created the parent object when defining the child object's prototype.
One work-around is of course to not use inheritance at all but use decorator functions as if they were constructors:
function new_person (name) {
var self = {};
self.name = name;
return self;
}
function new_accountant (name) {
var self = new_person(name);
return self;
}
This design pattern is often called parasitic inheritance. Notice that in this design pattern we don't use the keyword new
.
Another work-around, if you still want to use proper inheritance, is for objects to have an init
function that can be called by any constructor that wants to inherit it:
function Person (name) {
this.init(name);
}
Person.prototype.init = function (name) {
this.name = name;
}
function Accountant (name) {
this.init(name);
}
Accountant.prototype = new Person('');
There are other, more fancy work-arounds of course. This being javascript, you're only limited by your creativity. But for prototype inheritance the init function looks like the simplest work-around requiring minimal code without needing additional libraries or a new version of the language.