I've read a lot of stuff about mixins, inheritance and such, and in the end I came up with this solution for extending a class with multiple mixins. I haven't seen this anywhere else...
var Classes = {}; // I keep all classes inside this objects, so I can do new Classes[obj_name]();
Classes.asA = function () {
var _init = this.init; // keep a copy of the previously declared method, if any
this.init = function (a) {
if (_init) _init.call(this, a); // call super method, if any
this.a = a; // declare additional properties here
}
this.methodA = function () {
console.log("a: "+this.a);
}
}
Classes.asB = function () {
var _init = this.init;
this.init = function (a) {
if (_init) _init.call(this, a);
this.b = a+1;
}
this.methodB = function () {
console.log("b: "+this.b);
}
}
Classes.Obj = function () {
var _init = this.init;
this.init = function (a) {
if (_init) _init.call(this, a);
this.z = a-2;
}
this.methodZ = function () {
console.log("z: "+this.z);
}
}
Classes.asA.call(Classes.Obj.prototype); // extend Obj with asA
Classes.asB.call(Classes.Obj.prototype); // extend Obj with asB
var obj = new Classes.Obj();
obj.init(7); // will call in order asA.init, asB.init, Obj.init
obj.methodA(); // outputs "a: 7"
obj.methodB(); // outputs "b: 8"
obj.methodZ(); // outputs "z: 5"
Is this a good method? Do you see any problems with it?