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");
I don’t know if I call
bd.collection.example.method()will work becauseexampleis a constant and does not belong to the methods ofcollection, now if you’ll callexample.method()will work only if the value ofmethodis a function.– Douglas Garrido
@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 forconst examplewhich will have the name gives function that thecollectionhas and executes it– Guilherme Escarabel
Then you assign the function
exampleto a "generic" property ofcollection. Example:collection.myFunction = example.method. So you’ll be able to call:collection.myFunction(), for propertymyFunctionwill be part of yourcollectionand it is the function received fromexample.method.– Douglas Garrido