Even smaller class helper
by julienrf
JavaScript
var Base = (function () {
function Base () {};
Base.prototype.init = Base.prototype.constructor; // Empty default constructor
Base.extend = function (methods) {
var parentPrototype = this.prototype;
var Child = function () {
this._super = parentPrototype;
this.init.apply(this, arguments);
};
// Wire the Child prototype on a copy of this prototype
Child.prototype = Object.create(parentPrototype);
// Set methods to the Child’s prototype
for (var m in methods) {
Child.prototype[m] = methods[m];
}
// Add the static extend method
Child.extend = this.extend;
// That’s all
return Child;
};
return Base;
})();
var Sub = Base.extend({
init: function (spec) {
this.foo = spec.foo;
},
bar: function () {
return this.baz();
},
baz: function () {
return this.foo;
}
});
var sub = new Sub({ foo: 'foo' });
var SubSub = Sub.extend({
baz: function () {
return 'bazbaz' + this._super.baz.call(this);
}
});
var subsub = new SubSub({ foo: 'foofoo' });
console.log(sub.bar());
console.log(subsub.bar());
console.log(sub instanceof SubSub, subsub instanceof SubSub);