Call an object function from a text variable
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开发者_C百科 do that? the example doesn't work for me.
Use 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');
}
精彩评论