Skip to content

Instantly share code, notes, and snippets.

@vinniefranco
Created January 23, 2012 06:05
Show Gist options
  • Save vinniefranco/1661041 to your computer and use it in GitHub Desktop.
Save vinniefranco/1661041 to your computer and use it in GitHub Desktop.
// 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