Skip to content

Instantly share code, notes, and snippets.

@leegrey
Last active October 12, 2015 21:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leegrey/4091430 to your computer and use it in GitHub Desktop.
Save leegrey/4091430 to your computer and use it in GitHub Desktop.
inherit.js - a minimal prototype inheritance utility
/*
Inherit copyright 2012 by Lee Grey
license: MIT
http://creativecommons.org/licenses/MIT/
http://opensource.org/licenses/mit-license.php
The goal of the Interit class is to allow for a prototype based inheritance that
does not create a deep prototype chain. Inherited fields are known to be slow,
so methods and fields are simply copied onto the prototype of the target,
keeping only a single depth.
Usage:
function A(){}
A.prototype = {
foo : function () {
//...
}
}
function B(){
// call "super()":
A.call(this);
}
Inherit.from(B, A);
You can also inherit from multiple parents and plain objects:
Inherit.from(B, A, {
foo : function () {
// call super function:
A.prototype.foo.call(this);
//...
}
bar : function () {
//...
}
});
Note that parents are overlayed in the order supplied, from left to right
*/
var Inherit = Inherit || {};
Inherit.from = function () {
if( arguments.length < 2 ) return;
var target = arguments[ 0 ];
var parent;
for ( i = 1; i < arguments.length; i++ ) {
parent = arguments[ i ];
// If parent is a functional object, copy
// from parent.prototype into the target.prototype:
if( typeof parent === 'function' ) {
for ( var name in parent.prototype ) {
target.prototype[ name ] = parent.prototype[ name ];
}
// copy props from parent into the target
// ( ie static vars and methods )
for ( var name in parent ) {
target[ name ] = parent[ name ];
}
}
//if it is an object, apply to the prototype
else if( typeof parent === 'object' ) {
for ( var name in parent ) {
target.prototype[ name ] = parent[ name ];
}
}
}
}
@leegrey
Copy link
Author

leegrey commented Jul 17, 2013

Note, this is a simplified version of the earlier Inherit.js, with only the core functionality.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment