admin管理员组文章数量:1317579
app = {
echo: function(txt) {
alert(txt)
},
start: function(func) {
this.func('hello');
}
}
app.start('echo');
I need to call whatever function passed as func. How to do that? the example doesn't work for me.
app = {
echo: function(txt) {
alert(txt)
},
start: function(func) {
this.func('hello');
}
}
app.start('echo');
I need to call whatever function passed as func. How to do that? the example doesn't work for me.
Share Improve this question edited Feb 19, 2011 at 12:18 Radek 8,3864 gold badges34 silver badges42 bronze badges asked Feb 19, 2011 at 12:13 CodeOverloadCodeOverload 48.6k56 gold badges133 silver badges223 bronze badges 1- Do you have to use strings? Why can't you just pass the function to call? – user395760 Commented Feb 19, 2011 at 12:38
4 Answers
Reset to default 8Use this[func]
instead of this.func
app={
echo:function(txt){
alert(txt)
},
start:function(func){
this[func]('hello');
}
}
app.start('echo');
I guess in it's simplest form you could do:
var app =
{
echo: function(txt)
{
alert(txt);
},
start: function(func)
{
this[func]("hello");
}
};
But you could get a little smarter with the arguments:
var app =
{
echo: function(txt)
{
alert(txt);
},
start: function(func)
{
var method = this[func];
var args = [];
for (var i = 1; i < arguments.length; i++)
args.push(arguments[i]);
method.apply(this, args);
}
};
That way you can call it as app.start("echo", "hello");
Try that way:
start: function(func) {
this[func]('hello');
}
start:function(func){
this[func]('hello');
}
本文标签: javascriptCall an object function from a text variableStack Overflow
版权声明:本文标题:javascript - Call an object function from a text variable - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742019695a2414430.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论