Created
August 17, 2011 22:20
-
-
Save coverslide/1152788 to your computer and use it in GitHub Desktop.
A simple object wrapper that converts functions that return `undefined` to return an instance of the object instead, `chainifying` those calls
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
function chainify(obj, that){ | |
if(typeof obj === 'object'){ | |
that = that || {__object: obj} | |
for(var i in obj){ | |
if(typeof obj[i] === 'function'){ | |
that[i] = function(){ | |
var ret = that.__object[i].apply(that.__object, arguments) | |
if(typeof ret === 'undefined') | |
return that | |
return ret | |
} | |
} | |
} | |
chainify(Object.getPrototypeOf === 'function' ? Object.getPrototypeOf(obj) : obj.__proto__, that) | |
return that | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In the Java world, we call this "fluent API". Some open source projects work this way like XMLSlurper, RestAssured, Commons CSV, JOOQ, jRTF, etc.