Object.prototype.super = function(method, argsObj) {
var inst = this;
var r = null;
if (inst.p == this.__proto__) {
inst.pp = inst.pp.__proto__;
} else {
inst.p = this.__proto__;
inst.pp = this.__proto__.__proto__;
}
if (inst.pp != null) {
var tmp = inst.pp.__proto__;
inst.pp.__proto__ = null;
if (typeof(inst.pp[method]) != "function") {
inst.pp.__proto__ = tmp;
this.super(method, argsObj);
}
inst.pp.__proto__ = tmp;
this.superMethod = inst.pp[method];
r = this.superMethod(argsObj);
}
delete this.superMethod;
delete inst.p;
delete inst.pp;
return r;
};
ASSetPropFlags(Object.prototype, ["super"], 1);
//-------------------------------------------------------------------
Object.prototype.inherits = function(superclass, argsObj) {
this.tmpBase = superclass;
this.tmpBase(argsObj);
delete this.tmpBase;
};
ASSetPropFlags(Object.prototype, ["inherits"], 1);
Object.extends = function(subclass, superclass) {
subclass.prototype.__proto__ = superclass.prototype;
};
//-------------------------------------------------------------------
function ClassA(argsObj) {
this.a = argsObj.a;
};
ClassA.prototype.setProp = function(a) {
this.a = a;
};
ClassA.prototype.getProp = function() {
return this.a;
};
//-------------------------------------------------------------------
function ClassB(argsObj) {
this.inherits(ClassA, {a:argsObj.a});
this.b = argsObj.b;
};
Object.extends(ClassB, ClassA);
ClassB.prototype.setProp = function(b) {
this.b = b;
};
ClassB.prototype.getProp = function() {
return this.super("getProp") +","+ this.b;
};
//-------------------------------------------------------------------
function ClassC(argsObj) {
this.inherits(ClassB, {a:argsObj.a, b:argsObj.b});
this.c = argsObj.c;
};
Object.extends(ClassC, ClassB);
ClassC.prototype.setProp = function(c) {
this.c = c;
};
ClassC.prototype.getProp = function() {
return this.super("getProp") +","+ this.c;
};
//-------------------------------------------------------------------
function ClassD(argsObj) {
this.inherits(ClassC, {a:argsObj.a, b:argsObj.b, c:argsObj.c});
this.d = argsObj.d;
};
Object.extends(ClassD, ClassC);
ClassD.prototype.setProp = function(d) {
this.d = d;
};
ClassD.prototype.getProp = function() {
return this.super("getProp") +","+ this.d;
};
//-------------------------------------------------------------------
var obj= new ClassD({a:"A", b:"B", c:"C", d:"D"});
for (var p in obj)
trace(p +":"+ obj[p]);
trace(obj.getProp());
obj.setProp("E");
trace(obj.getProp());
|
|
// Trace output:
getProp:
setProp:
getProp:
setProp:
getProp:
setProp:
getProp:
setProp:
d:D
c:C
b:B
a:A
A,B,C,D
A,B,C,E
|
|
Notes:
The use of argsObj (an object) instead of individual arguments parameters is just another approach to passing parameters. The problem with a pre-determined number of arguments in the function is the property arguments.length will always be that fixed number, no matter how many arguments are passed.
Download source file: superInherit.zip
See also: Different ways to inherit
|