Skip to content

Instantly share code, notes, and snippets.

@AutoSponge
Created November 28, 2012 19:38
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 AutoSponge/4163551 to your computer and use it in GitHub Desktop.
Save AutoSponge/4163551 to your computer and use it in GitHub Desktop.
Inheritance pattern
(function (namespace) {
"use strict";
function Class() {}
Class.prototype = {
constructor: Class
};
Class.extend = function (fn) {
if (!fn.name) {
fn.name = fn.toString()
.replace(/function |\([^\0]+/g, "") || "anonymous";
}
namespace[fn.name] = fn;
fn._super = this;
fn.extend = this.extend;
fn.inherit = this.inherit;
fn.prototype = new fn._super();
fn.prototype.constructor = fn;
return fn;
};
Class.inherit = function (obj) {
for (var o in obj) {
if (obj.hasOwnProperty(o)) {
this.prototype[o] = obj[o];
}
}
return this;
};
namespace.Class = Class;
}(this));
Class.extend(function A() {
if (this.constructor === A) {
this.step1();
}
}).inherit({
step1: function () {
this._step1 = 1;
},
aMethod: function () {}
}).extend(function B() {
B._super.apply(this, arguments);
if (this.constructor === B) {
this.step2();
}
}).inherit({
step2: function () {
this._step2 = 2;
},
bMethod: function () {}
}).extend(function C() {
C._super.apply(this, arguments);
if (this.constructor === C) {
this.step3();
}
}).inherit({
step3: function () {
this._step3 = 3;
},
cMethod: function () {}
});
var c = new C();
/*
note:
* object c is an instance of A, instance of B, and instance of C
* object c has the _step1, _step2, and _step3 properties (but not all at the object level)
* object c has all inherited and extended methods
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment