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');
}