Skip to content

Instantly share code, notes, and snippets.

@dsheiko
Created May 24, 2012 09:27
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 dsheiko/2780447 to your computer and use it in GitHub Desktop.
Save dsheiko/2780447 to your computer and use it in GitHub Desktop.
Prototypal Inheritance for Modules
/**
* Prototypal Inheritance for Modules
*
* Prototypal inheritance in its generic case was described by Douglas Crockford at http://javascript.crockford.com/prototypal.html
* However it doesn't work with modules (http://addyosmani.com/largescalejavascript/). This implementation allows to inherit from modules
*
* @author Dmitry Sheiko
* @version object-create-from-module.js, v 1.0
* @license MIT
* @copyright (c) Dmitry Sheiko http://dsheiko.com
**/
(function(){
"use strict";
Function.prototype.createInstance = function () {
var key, module = this, members = module.apply(this, arguments), Fn = function () {};
members.hasOwnProperty( "__extends__" ) && members[ "__extends__" ]
&& (module.prototype = members[ "__extends__" ].createInstance());
Fn.prototype = module.prototype; // Link to the supertype
for (key in members) { // Mix in members
if (members.hasOwnProperty(key)) {
Fn.prototype[key] = members[key];
}
}
return new Fn();
};
// Usage example
var AbstractModule = function () {
return {
inheritedProp : "inherited property",
publicProp : "original property"
};
},
ConcreteModule = function () {
var _privateVar = "private";
return {
__extends__: AbstractModule, // ConcreteModule extends AbstractModule
getPrivate : function () {
return _privateVar;
},
publicProp : "overriden property"
};
};
// Make an instance of ConcreteModule
var o = ConcreteModule.createInstance();
console.log(o instanceof ConcreteModule); // true
console.log(o instanceof AbstractModule); // true
console.log(o.getPrivate()); // private
console.log(o.publicProp); // overriden property
console.log(o.constructor.prototype.publicProp); // original property
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment