How to use functions and their values as parameters?

I want an object to call a function defined in another object or JSON (as a string or reference), with a variable number of values also defined there.

Here’s a pseudo-code example of what I’m trying to do:

// function name and variable-length values definition
const definition = {
  functionName: "function1",
  values: [ 1, "foo", 3.14 ]

// objectA calling the function with the values
// objectA.definedFunction(definedValues);
// objectA.[functionName]([val1], [val2], ..., [valN]);
objectA.function1(1, "foo", 3.14);

Note: objectA may/should? reference the definition in a member variable.

How can that be achieved?

And is it possible to expand that so that function1 is a member function of another object that is also defined in definition?


There are two mechanisms you need.

First the square bracket notation to access object properties:

objectA[definition.functionName]; // this will return the function you want
// This is the same as objectA.function1

Second you want to pass an array as parameter list. For that you can use Function.prototype.apply which expects the argument list in the form of an array:

objectA[definition.functionName].apply(objectA, definition.values);
// This is the same as objectA.function1(1, "foo", 3.14);

Leave a Reply

Your email address will not be published. Required fields are marked *