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 becauseexample
is a constant and does not belong to the methods ofcollection
, now if you’ll callexample.method()
will work only if the value ofmethod
is 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 example
which will have the name gives function that thecollection
has and executes it– Guilherme Escarabel
Then you assign the function
example
to a "generic" property ofcollection
. Example:collection.myFunction = example.method
. So you’ll be able to call:collection.myFunction()
, for propertymyFunction
will be part of yourcollection
and it is the function received fromexample.method
.– Douglas Garrido