Skip to content

Instantly share code, notes, and snippets.

Created December 23, 2012 13:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/4363392 to your computer and use it in GitHub Desktop.
Save anonymous/4363392 to your computer and use it in GitHub Desktop.
A Javascript inheritance function. Derived by joining some parts by John Resig http://ejohn.org/ and some by Ajax.org Code Editor (ACE) Source. The end result: When you call `inherits` each overridden method in the derived class can call it's super-method by using this._super.
/* JavaScript Inheritance
* Author: Mutahhir Ali Hayat
* Made by joining some parts by John Resig http://ejohn.org/ and some by Ajax.org Code Editor (ACE)
*/
define(function(require, exports, module) {
var initializing = false,
fnTest = /xyz/.test(function() {
xyz;
}) ? /\b_super\b/: /.*/;
exports.inherits = (function() {
var tempCtor = function() {};
return function(ctor, superCtor) {
tempCtor.prototype= superCtor.prototype;
var prop = ctor.prototype,
_super = superCtor.prototype,
prototype = new tempCtor();
for(var name in prop) {
prototype[name] =
typeof prop[name] === "function" &&
typeof _super[name] === "function" &&
fnTest.test(prop[name])?
(function(name, fn){
return function(){
var tmp = this._super;
this._super = _super[name];
var ret = fn.apply(this, arguments);
this._super = tmp;
return ret;
}
})(name, prop[name]) : prop[name];
}
ctor.prototype = prototype;
ctor.prototype.constructor = ctor;
return ctor;
}
})();
});
/* ----
This is an excerpt from a javascript library called Cotton I made. Not opensourced yet.
Layer is the base class and Stack is the derived class.
Just FYI: A stack is a kind of layer that automatically ensures that all children are placed vertically one after the other
---- */
define(function(require, exports, module) {
var oop = require("cotton/oop");
var Layer = require('cotton/layer').Layer;
var Stack= function(parent, options){
if (!(this instanceof Stack)) {
return new Stack(parent, options);
}
Layer.apply(this, arguments);
};
(function(){
// add prototype functions here
this._createElement = function _createElement() {
var el = this._super.apply(this, arguments);
$(el).addClass('stack');
return el;
};
}).call(Stack.prototype);
oop.inherits(Stack, Layer);
exports.Stack = Stack;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment