Calling 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 any function passed as func. How to do it? for me this example does not work.

+3
source share
4 answers

Use this[func]insteadthis.func

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

      app.start('echo');
+8
source

I assume this is a simple form you could do:

var app =
{
  echo: function(txt)
  {
    alert(txt);
  },

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

But you could argue a little smarter:

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

So you can call him app.start("echo", "hello");

+4
source

Try the following:

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

Source: https://habr.com/ru/post/1793225/


All Articles