Skip to content

Instantly share code, notes, and snippets.

@kkoziarski
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kkoziarski/b51042029308917a89e5 to your computer and use it in GitHub Desktop.
Save kkoziarski/b51042029308917a89e5 to your computer and use it in GitHub Desktop.
Function.prototype.method - The Good Parts
Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
};
// Add a method conditionally.
Function.prototype.method = function (name, func) {
if (!this.prototype[name]) {
this.prototype[name] = func;
}
};
//EXAMPLES
Number.method('integer', function ( ) {
return Math[this < 0 ? 'ceiling' : 'floor'](this);
});
document.writeln((-10 / 3).integer( )); // -3
//JavaScript lacks a method that removes spaces from the ends of a string.
//That is an easy oversight to fix:
String.method('trim', function ( ) {
return this.replace(/^\s+|\s+$/g, '');
});
document.writeln('"' + " neat ".trim( ) + '"');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment