Home > Software engineering >  How can I use a string to call a method in Node JS
How can I use a string to call a method in Node JS

Time:01-29

I have a function that returns a string of a method I want to call.

For example:

I call the function and it returns the string "price". I then want to use the word price to call another method ( contractObject.price() )

Is there any way to accomplish this in Node JS?

CodePudding user response:

Yes, you can use square brackets:

let methodName = "price";

contractObject[methodName]();

contractObject["price"] is equivalent to contractObject.price.

CodePudding user response:

This will work.

const functionToCall = yourFunction(); // this returns "price"
// call the price function like this
contractObject[functionToCall]();

CodePudding user response:

Ended up figuring out the answer. If I make the whole function a string and then use eval( ) it calls the method I wanted

  •  Tags:  
  • Related