Reputation: 961
I'm using js.class and i want to be able to call functions of super class in the sub class. I know i can use this.callSuper()
to call the current overridden function from the super class but what about calling other overridden functions?
For example in Java i can do this:
class SuperClass {
void myMethod() {
// Do something!
}
}
class SubClass extends SuperClass {
void myMethod() {
// Do something else!
}
void anotherMethod() {
super.myMethod(); // call the original myMethod form the SuperClass
}
}
Is it possible in js.class?!
Upvotes: 1
Views: 165
Reputation: 18783
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);
Upvotes: 1
Reputation: 11245
You can make it without js.class
if you know what A
is super of B
:
A = function (x) { this.x = x};
A.prototype.myMethod = function () {return this.x + 1};
B = function (x) { A.call(this,x)};
B.prototype = new A();
B.prototype.myMethod = function () {return this.x + 2};
B.prototype.anotherMethod = function () {return A.prototype.myMethod.call(this)};
If you don't know who is parent of B you can use __proto__
where it supports:
B.prototype.anotherMethod = function () {this.__proto__.myMethod.call(this)};
If you really need js.class
try this(checking this right now):
var A = new Class({
extend: {
inherited: function(childClass) {
childClass.super = this.klass;
}
},
initialize: function(x) {
this.x = x;
},
myMethod: function() {
return this.x + 1;
}
});
var B = new Class(A, {
initialize: function(x) {
this.callSuper(x);
},
myMethod: function() {
return this.x + 2;
},
anotherMethod: function () {
return this.super.myMethod()
}
});
Upvotes: 1