i tried to find a way to call overridden method of superclass in JS and got this.
function A() {
this.superclass = new Array(A.prototype);
}
A.prototype.call_method = function(method, args, pos) {
if (!(pos >= 0)) pos = this.superclass.length - 1;
while (!this.superclass[pos].hasOwnProperty(method)) if ((--pos) < 0) return;
if (this.superclass[pos][method]) this.superclass[pos][method].apply(this, args);
if (pos) this.call_method(method, args, pos - 1);
}
A.prototype.add = function() {
this.superclass.push(arguments.callee.caller.prototype);
}
A.prototype.test = function(a, b, c) {
alert("test of A ");
}
function B() {
A.call(this);
this.add();
}
B.prototype = new A();
B.prototype.constructor = B;
B.prototype.test1 = function(a, b, c) {
alert("test of B ");
}
function C() {
B.call(this);
this.add();
}
C.prototype = new B();
C.prototype.constructor = C;
C.prototype.test = function(a, b, c) {
alert("test of C");
}
var aa = new C();
aa.call_method("test", [1, 2, 3]);
What do You think, is it ok ? Or maybe it can produce 'memory leaks' (reference to own prototype)? Thanks a lot
Thank You for your reply, i tried Your code out . But if I subclass SubClass, for examle var a= SubClass1(), ( SubClass1 has its own foo())
and call a.foo(), then only SubClass1 and BaseClass foo's will be called,
not SubClass foo() Code:
function BaseClass() { } BaseClass.prototype.foo = function() {
alert('called BaseClass.foo');
};
SubClass = function() { };
SubClass.prototype = new BaseClass;
SubClass.prototype.foo = function() {
alert('called SubClass.foo');
// calling super.foo();
this.constructor.prototype.foo.call(this);
};
SubClass1 = function() { };
SubClass1.prototype = new SubClass;
SubClass1.prototype.foo = function() {
alert('called SubClass1.foo');
// calling super.foo();
this.constructor.prototype.foo.call(this);
};
var a=new SubClass1();
a.foo();
Thanks