Skip to content

Instantly share code, notes, and snippets.

@namusyaka
Created April 16, 2011 09:21
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 namusyaka/923009 to your computer and use it in GitHub Desktop.
Save namusyaka/923009 to your computer and use it in GitHub Desktop.
RubyのObject.sendみたいなのをJavaScriptで実装
function a(b){
alert(b)
}
Object.prototype.send = function(method, args) {
var args = args instanceof Array ? args : [args]
return this[method].apply(this, args)
}
function send(func, args) {
var func = /\./.test(func) ? func.split(".") : func;
var args = args instanceof Array ? args : [args]
if(func instanceof Array) {
var nest = window;
for(var i = 0; i < func.length; i++)
nest = nest[func[i]];
return nest.apply(func[func.length - 1], args)
}
return window[func].apply(null, args)
}
bd = {
c : function(d, e) {
alert(d + e)
}
}
send("a", ["v","f"]);
send("bd.c", ["foo", "bar"]);
alert("a,b,c".send("split", ",")[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment