Yes it is possible, with a little knowledge about how "classes" work in JavaScript.
JavaScript Class Basics
(you can skip this part if you already know this)
A "class" in JavaScript is really just a Function object that has a property called prototype
. This prototype
property provides that default instance methods and properties.
Let's take two example classes, Point
and Point3D
.
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype = {
x: 0,
y: 0,
constructor: Point,
isAbove: function(point) {
return this.y > point.y;
},
isBelow: function(point) {
return this.y < point.y;
}
};
The Point
class is our base class, representing an x and a y coordinate. The Point3D
class inherits from Point
and has a z coordinate (ignoring any mathematical inaccuracies).
function Point3D(x, y, z) {
Point.call(this, x, y);
this.z = z;
}
Point3D.prototype = new Point(0, 0);
Point3D.prototype.constructor = Point3D;
Point3D.prototype.isAbove = function(point) {
return Point.prototype.isAbove.call(this, point);
};
Point3d.prototype.isDiagonal = function(point) {
return Point.prototype.isAbove.call(this, point)
&& this.x > point.x;
};
In the isDiagonal
method, we call the isAbove
method on the Point class, even though Point3D implements its own version.
Calling the Overridden Method
You can call any overridden method on any class by using this basic template:
ClassName.prototype.method.call(this, arg1, arg2, ... argN);