Ask Your Question
0

How can one obtain the function-object of a JavaScript function that is identified by its name in string format?

asked 2021-04-12 11:00:00 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2021-05-04 22:00:00 +0000

pufferfish gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-04-12 11:00:00 +0000

Seen: 24 times

Last updated: May 04 '21