开发者

Call an object function from a text variable

开发者 https://www.devze.com 2023-02-11 21:26 出处:网络
app = { echo: function(txt) { alert(txt) }, start: function(func) { this.func(\'hello\'); } } app.start(\'echo\');
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');
}
0

精彩评论

暂无评论...
验证码 换一张
取 消