Skip to content

Instantly share code, notes, and snippets.

@invernizzie
Last active December 16, 2015 02:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save invernizzie/5360735 to your computer and use it in GitHub Desktop.
Save invernizzie/5360735 to your computer and use it in GitHub Desktop.
Inheritance models that provides: - Use of the new operator. - Proper prototype chain and public methods attached to the prototype. - Private methods (through Function.prototype.call or Function.prototype.apply). - Class._super_ attribute to access base class' prototype (for calling super-methods easily).
var inherit = function (init) {
var base, ctor;
base = this;
ctor = function () {
if (typeof init === 'function') {
init.apply(this, arguments);
}
};
ctor.prototype = new base();
ctor._super_ = base.prototype;
ctor.inherit = inherit;
return ctor;
}
var Base = (function() {
// TODO: Prevent calling without new.
var Base = function () {}
function private () {
console.log(this.foo);
}
Base.prototype.public = function (name) {
console.log("Base's public " + name);
private.apply(this);
};
Base.prototype.aMethod = function () {
console.log("Base method");
}
return Base;
})();
Base.inherit = inherit;
var Child = (function () {
var Child = Base.inherit(function (){
this.foo = 'bar';
});
Child.prototype.public = function (name) {
console.log("Child's public");
Child._super_.public.call(this, name);
};
return Child;
})();
var Third = Child.inherit();
var Base = (function() {
// TODO: Prevent calling without new.
var Base = function () {}
function private () {
console.log(this.foo);
}
Base.prototype.public = function (name) {
console.log("Base's public " + name);
private.apply(this);
};
return Base;
})();
var Child = (function () {
var Child;
Child = function () {
this.foo = 'bar';
};
Child._super_ = Base.prototype;
// Here we set the prototype chain straight and enable inheritance.
Child.prototype = new Base();
Child.prototype.public = function (name) {
console.log("Child's public");
Child._super_.public.call(this, name);
};
return Child;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment