Well, a way that you can re-use the logic of the Person
constructor is invoking it with call
or apply
, for example:
function Person(gender) {
this.gender = gender;
}
function Student(gender) {
Person.apply(this, arguments);
}
Student.prototype = new Person(); // make Student inherit from a Person object
Student.prototype.constructor = Student; // fix constructor property
var foo = new Student('male');
foo.gender; // "male"
foo instanceof Student; // true
foo instanceof Person; // true
If you want to prevent the execution of the Person
constructor when is called without arguments (like in the line: Student.prototype = new Person();
), you can detect it, e.g.:
function Person(gender) {
if (arguments.length == 0) return; // don't do anything
this.gender = gender;
}