How to access a non-explicit function

1

I apologize for the very generic title, but I can not express it in a short way and that is why my searches were a failure.

Let's get down to an example:

bd.colection.find();

I'm trying instead to explicitly declare find (), do so:

const example = {method: 'find'};
bd.collection.example.method();

Access one function per string, something like

    
asked by anonymous 10.02.2017 / 13:27

1 answer

1

If I understand correctly, the problem is to call a bd.collection method, via a string , with the method name, which probably comes from another code location. Something like: call the specified method in example.method , whatever it is.

Suppose the situation:

var bd = {
  collection: {
    find: function (keyword) {
      console.log(keyword);
    }
  }
}

Where the method is specified in:

const example = {method: "find"};

One way is to access the object by index, through the method name:

bd.collection[example.method]("SOpt");

That generates exactly the same output as the direct call of the method:

bd.collection.find("SOpt");

Below, I've entered the complete code to be able to run.

var bd = {
  collection: {
    find: function (keyword) {
      console.log(keyword);
    }
  }
}

const example = {method: "find"};

bd.collection[example.method]("SOpt");
bd.collection.find("SOpt");
    
10.02.2017 / 14:07