Skip to content

Instantly share code, notes, and snippets.

@rbishop
Created January 24, 2013 04:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rbishop/4617791 to your computer and use it in GitHub Desktop.
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?
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