Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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