Skip to content

Instantly share code, notes, and snippets.

@bbuecherl
Last active August 29, 2015 14:14
Show Gist options
  • Save bbuecherl/69a4bdc91d44b9770589 to your computer and use it in GitHub Desktop.
Save bbuecherl/69a4bdc91d44b9770589 to your computer and use it in GitHub Desktop.
JS-classes with multiple inheritance, super method and more
var ExampleClass = utils.Class(function(con, struc, tor) {
this.super([], [struc]);
this.con = con;
this.tor = tor;
}, [events.EventEmitter, OtherClass], {
print: function() {
return this.con + this.tor;
}
});
var utils = module.exports = {
Class: function(c, extending, methods) {
var D = function() {
if(!(this instanceof D)) {
var E = function(args) { D.apply(this, args); };
E.prototype = D.prototype;
return new E(arguments);
}
c.apply(this, arguments);
};
if(!methods) {
D.prototype = extending;
} else {
D.prototype = {
super: function() {
if(Object.prototype.toString.call(extending) === "[object Array]") {
for(var i = 0; i < extending.length; ++i) {
extending[i].apply(this, arguments[i]);
}
} else {
extending.apply(this, arguments);
}
this.super = undefined;
}
};
if(Object.prototype.toString.call(extending) === "[object Array]") {
var proto = {};
for(var i = 0; i < extending.length; ++i) {
utils.Mixin(proto, extending[i].prototype);
}
D.prototype.__proto__ = proto;
} else {
D.prototype.__proto__ = extending.prototype;
}
for(var m in methods) {
if(methods.hasOwnProperty(m) && !D.prototype.hasOwnProperty(m)) {
D.prototype[m] = methods[m];
}
}
}
return D;
},
Mixin: function(mix, ins) {
if(ins) {
for(var m in ins) {
if(ins.hasOwnProperty(m)) {
mix[m] = ins[m];
}
}
}
return mix;
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment