How to access a non-explicit function

Asked

Viewed 34 times

1

I apologize for the very generic title, but I do not know how to express it in a short way and it is for this reason that my research was a failure.

Let’s get to an example:

bd.colection.find();

I am trying instead of explicitly stating find(), to do so:

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

Access a function by string, something like that

  • I don’t know if I call bd.collection.example.method() will work because example is a constant and does not belong to the methods of collection, now if you’ll call example.method() will work only if the value of method is a function.

  • @Douglasgarrido this is my problem, I want to access a function of collection, but I don’t know what that role will be, the role will stay for const example which will have the name gives function that the collection has and executes it

  • Then you assign the function example to a "generic" property of collection. Example: collection.myFunction = example.method. So you’ll be able to call: collection.myFunction(), for property myFunction will be part of your collection and it is the function received from example.method.

1 answer

1


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

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

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

bd.collection.find("SOpt");

Below, I entered the complete code to be executed.


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

const example = {method: "find"};

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.