3
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.

1
  • Do you have to use strings? Why can't you just pass the function to call? Commented Feb 19, 2011 at 12:38

4 Answers 4

8

Use this[func] instead of this.func

   app={
          echo:function(txt){
          alert(txt)
          },
         start:function(func){
            this[func]('hello');
          } 
        }

      app.start('echo');
Sign up to request clarification or add additional context in comments.

Comments

4

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");

1 Comment

You can also use arrays slice instead of manually looping through arguments array, even tho not directly var args = Array.prototype.slice.call(arguments, 1);
2

Try that way:

start: function(func) {
    this[func]('hello'); 
}

Comments

2
start:function(func){
this[func]('hello');
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.