Created
January 24, 2013 04:59
-
-
Save rbishop/4617791 to your computer and use it in GitHub Desktop.
So, everything is an object eh, JavaScript? Then every object should have a send method! This is just for fun of course and I pray to not be punished by the gods for extending native prototypes. How fun is it to have a ton of dynamic method dispatching at your hands though?
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
Object.prototype.send = function(methodName) { | |
args = [].slice.call(arguments); | |
args.shift() | |
if (this.hasOwnProperty(methodName)) return this[methodName]; | |
if (args.length > 1) { | |
return this[methodName].apply(this, args); | |
} else { | |
return this[methodName](); | |
} | |
}; | |
var str = 'Hello'; | |
str.send('replace', 'll', 'r'); | |
// => 'hero' | |
str.send('slice', 0, 4); | |
// => 'Hell' | |
var arr = ['Please', "Don't", 'Kill', 'Me', 'JavaScript', 'Purists'] | |
arr.send('length') | |
// => 6 | |
arr.send('sort') | |
// => ["Don't", "JavaScript", "Kill", "Me", "Please", "Purists"] | |
var methods = ['toUpperCase', 'length'] | |
methods.map(function(element) { return str.send(element) }); | |
// => ['HELLO', 5] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment