Created
January 23, 2012 06:05
-
-
Save vinniefranco/1661041 to your computer and use it in GitHub Desktop.
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
// Shorter cleaner way to add methods to an object prototype. Thank you Crockford | |
Function.prototype.method = function ( name, func ) { | |
if (! this.prototype[name] ) { this.prototype[name] = func; return this; } | |
}; | |
// And here's the ability to add multiple KVs to objects | |
Function.method( "methods", function ( obj ) { | |
if ( typeof obj !== "object" ) return; | |
for ( var key in obj ) { | |
if ( ! obj.hasOwnProperty( key ) ) continue; | |
this.method( key, obj[key] ); | |
} | |
}); | |
// Example usage | |
String.methods({ | |
'to_i': function () { return parseInt( this.match( /\d+/ )[0], 10 ); }, | |
'capitalize': function () { return this.charAt( 0 ).toUpperCase() + this.slice( 1 ); } | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment