Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

One can obtain the function-object of a JavaScript function that is identified by its name in string format using the following methods:

  1. Using the global window object: If the function is defined in the global scope, it can be accessed using the window object as shown below:
const myFunc = function() {
  console.log('Hello World!');
}

const funcName = 'myFunc';
const myFuncObj = window[funcName];
  1. Using the eval function: The eval function can be used to evaluate a string as code, and the result can be assigned to a variable to obtain the function object as shown below:
const myFunc = function() {
  console.log('Hello World!');
}

const funcName = 'myFunc';
const myFuncObj = eval(funcName);

It is important to note that using eval is not recommended as it can be a security risk, and should only be used when there is no other alternative.