Created
April 16, 2011 09:21
-
-
Save namusyaka/923009 to your computer and use it in GitHub Desktop.
RubyのObject.sendみたいなのをJavaScriptで実装
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 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