JS inheritance patterns...again
by wittnl
JavaScript
function Class(def) {
if(!(this instanceof Class))
return new Class(def);
this.def = def;
}
Class.prototype = {
extend2: function extend( parent ) {
var scope = this;
var fName = this.def.toString().substr('function '.length)
fName = fName.substr(0, fName.indexOf('('));
scope[fName] = function() {
parent.apply(scope.def, arguments);
};
var F = function() { scope.def.constructor = scope[fName] };
F.prototype = parent.prototype;
scope[fName].prototype = new F();
return scope[fName];
},
extend: function( parent) {
var scope = this;
var child = function() {
parent.apply(scope.def, arguments);
};
var F = function() { this.constructor = child; };
F.prototype = parent.prototype;
child.prototype = new F();
return child;
}
}
function A() {}
A.prototype.foo = true;
Class(B).extend(A);
function B() {}
//B.prototype.bar = true;
var test = new B();
console.log(test);