Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using JavaScript reflection to invoke a function

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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]();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading