'Using JavaScript reflection to invoke a function [duplicate]
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!
Solution 1:[1]
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]();
Solution 2:[2]
You can try:
function myFunctionName() {
// do something...
}
var myString = "myFunctionName()";
eval(myString)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Robby Cornelissen |
| Solution 2 | poppy |
