Last active
August 29, 2015 14:10
-
-
Save kkoziarski/b51042029308917a89e5 to your computer and use it in GitHub Desktop.
Function.prototype.method - The Good Parts
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.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