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
Add a ment  | 

4 Answers 4

Reset to default 8

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

本文标签: javascriptCall an object function from a text variableStack Overflow