-2

I am new to JavaScript and am struggling with how reflection works there. What I want to do is: Given a String which is the function's name, invoke that function. E.g. var myString = "myFunctionName()" is given and then I want to invoke myFunctionName() using myString somehow.

Is this possible and how?

Thanks in advance!

Intern
  • 1
  • 2
  • 1
    why do you want to do this? – erzen May 09 '22 at 09:06
  • Yes, it is possible if you know the scope/namespace that holds your function. Like `window[myString]()`. – Lain May 09 '22 at 09:06
  • @hxhzre I want to implement a DAG which has conditions on its edges and I want to store the whole thing in an array. The real usecase would be a wizard. I am not too sure whether that would lead to clean code so I am open to suggestions. – Intern May 09 '22 at 09:36

2 Answers2

-2

It all depends on the context in which the function is declared.

For the browser's window context:

function test() {
  console.log('Hello world!');
}

const string = 'test';

window[string]();
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
-2

You can try:

function myFunctionName() {
  // do something...
}

var myString = "myFunctionName()";

eval(myString) 
poppy
  • 61
  • 1
  • 7
  • You can try that, but be aware of the [risks](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval). – Lain May 09 '22 at 09:10