Inheritance in JavaScript with Constructor Arguments
JavaScript is not an class-based object-oriented programming language, but a prototype-based object-oriented language. There are a number of subtle and not-so-subtle differences between the two models that lead to a number of programming consequences. If you are unfamiliar with JavaScript prototypes, check out this nice discussion of the JavaScript object model in the Mozilla developer documentation.
Many JavaScript APIs, like the Google Maps API, expose a classical object hierachy using JavaScript prototypes. In JavaScript, object inheritance is acheived by copying the prototype of the superclass to the subclass, as described in the article above:
function Superclass() { this.x = 0; } Superclass.prototype.add = function(amount) { this.x += amount; } function Subclass() { } Subclass.prototype = new Superclass();
But what happens when the constructor of a superclass takes arguments? For example, say we defined Superclass
above like this:
function Superclass(initialValue) { this.x = initialValue; }
How do we subclass Superclass
now? What arguments do we provide in our inheritance line?
Subclass.prototype = new Superclass(???);
The answer is to define an inheritance helper method like this:
function inherit(subclass, superclass) { var c = function() {}; c.prototype = superclass.prototype; subclass.prototype = new c(); }
Then we would define Subclass
like this:
function Subclass(initialValue) { Superclass.call(this, initialValue); } inherit(Subclass, Superclass);
inherit
works by copying the prototype of Superclass
independently of the Superclass
function. You can call the constructor of the superclass by using the call
method, which is available for all JavaScript functions. The first argument to call
is the object instance this
, which ensures that this
will refer to the correct instance in the body of Superclass
.
Comments
What an ECMAcompatible browser should do with the following source ?
Superclass.prototype.add(amount) {
this.x += amount;
}
I guess, beside the missing ';', it should be :
Superclass.prototype.add = function(amount) { ... };
http://jslint.com/
This approach is supported by JSINER library - you can find more about it on http://www.soft-amis.com/jsiner/inheritance.html
Function.prototype.inherits = function(superclass) {
var x = function() {};
x.prototype = superclass.prototype;
this.prototype = new c();
}
Subclass.inherits(Superclass)
Write a Comment