Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subclassing a class with required parameters in JavaScript

Tags:

javascript

oop

If subclassing a "class" in JavaScript is done like so:

var ParentClass = function() {
    // something
};


var ChildClass = function() {
    // something
};

ChildClass.prototype = new ParentClass();

... what should I do when the parent class has required parameters?

var ParentClass = function(requiredParameter) {
    if (typeof requiredParameter === 'undefined') {
        throw new TypeError("'requiredParameter' is required!");
    }
};


var ChildClass = function() {
    // something
};

ChildClass.prototype = new ParentClass();
// ^ Throws TypeError

Thanks.

like image 215
Jonathan Chan Avatar asked Dec 10 '11 22:12

Jonathan Chan


1 Answers

This is how its done:

function Parent( a ) {
    this.a = a;
}

function Child( a, b ) {
    Parent.call( this, a ); // this is crucial
    this.b = b;
}

Child.prototype = Object.create( Parent.prototype );
Child.prototype.constructor = Child;

Live demo: http://jsfiddle.net/ECCgt/ (analyze the instances in the console)


The way you're doing it

ChildClass.prototype = new ParentClass();

is a dirty hack which is broken and should be avoided. Use Object.create to set up the inheritance relationship between the two prototype objects.

The second line

Child.prototype.constructor = Child;

is somewhat optional. We are correcting the constructor property because we had to overwrite Child.prototype in order to set up the inheritance. If you don't care about the constructor property, just leave out that line.

like image 102
Šime Vidas Avatar answered Nov 09 '22 15:11

Šime Vidas