Created
July 13, 2010 23:32
-
-
Save tbtlr/474740 to your computer and use it in GitHub Desktop.
Simple Ruby-style inheritance for JavaScript
This file contains hidden or 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
/* | |
* def.js: Simple Ruby-style inheritance for JavaScript | |
* | |
* Copyright (c) 2010 Tobias Schneider | |
* This script is freely distributable under the terms of the MIT license. | |
* | |
* | |
* Example: | |
* | |
* def ("Person") ({ | |
* init: function(){ ... } | |
* }); | |
* | |
* def ("Ninja") << Person ({ | |
* init: function(){ ... } | |
* }); | |
*/ | |
def = function(className){ | |
var base = window[className] = function(){ | |
if(this.constructor === base){ if(this.init){ this.init(arguments); } } | |
else{ | |
def._super = base; | |
def._props = arguments[0]; | |
} | |
}, | |
props = function(keyValues){ | |
if(def._super){ | |
var superclass = def._super; | |
def._super = def._props = null; | |
props(superclass.prototype); | |
props(keyValues); | |
}else{ | |
var proto = base.prototype; | |
for(var key in keyValues){ proto[key] = keyValues[key]; } | |
} | |
}; | |
props.valueOf = function(){ | |
this(def._props); | |
}; | |
return props; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment