Skip to content

Instantly share code, notes, and snippets.

@edubskiy
Created June 22, 2013 19:51
Show Gist options
  • Save edubskiy/5842347 to your computer and use it in GitHub Desktop.
Save edubskiy/5842347 to your computer and use it in GitHub Desktop.
Functional Prototype Inheritance Pattern
/**
* Functional Prototype Inheritance Pattern
* @author E.Dubskiy
* @email e.dubskiy@gmail.com
* @example:
* var Animal = new Class,
* Dog = new Class(Animal);
* Dog.include({
* bark: true
* });
* Now Marley has its prototype of Animal and also
* var Marley = new Dog;
*/
(function(exports, undefined) {
var _self = function(oParent) {
var _class = function() {
if (typeof this.init === 'function') {
this.init.apply(this, arguments);
}
}
// Modify class prototype
if (oParent) {
_class.prototype = Create(oParent);
}
// Create shortcuts
_class.fn = _class.prototype;
_class.fn.parent = _class;
_class._super = _class.__proto__;
_class.fn.init = function() {};
// Add inherited properties
_class.include = function(obj) {
var included = obj.included;
for(var i in obj) {
_class.fn[i] = obj[i];
}
if (included) included(_class);
}
// Add static properties
_class.extend = function(obj) {
var extended = obj.extended;
for (var i in obj) {
_class[i] = obj[i];
}
if (extended) extended(obj);
}
return _class;
}
exports.Class = _self;
exports.Create = exports.Object.create
? exports.Object.create
: (function() {
return function(o) {
var f = function() {};
f.prototype = o;
return new f();
}
})();
})(window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment