Skip to content

Instantly share code, notes, and snippets.

@tobitailor
Created July 13, 2010 23:32
Show Gist options
  • Save tobitailor/474740 to your computer and use it in GitHub Desktop.
Save tobitailor/474740 to your computer and use it in GitHub Desktop.
Simple Ruby-style inheritance for JavaScript
/*
* 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