Last active
October 12, 2015 21:47
-
-
Save leegrey/4091430 to your computer and use it in GitHub Desktop.
inherit.js - a minimal prototype inheritance utility
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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 ]; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note, this is a simplified version of the earlier Inherit.js, with only the core functionality.