1

How can i call a function whose definition is stored in string? e.g

var dynamicFun = `function Hello(person) {   return 'Hello' + person; }`

here the dynamicFun variable can hold any function definition dynamically e.g it can be

var dynamicFun = `function Sum(num) {   return num + num; }`

At compile time I would be not aware which function definition is assigned to dynamicFun variable. It is getting assigned at runtime so How can I call the above functions using dynamicFun variable with params (without knowing the actual function name or definition) in javascript/typescript.

1
  • @GrafiCode Yes it has my answer.Thanks :) Commented May 11, 2022 at 20:28

1 Answer 1

0

I would take a look at the Eval Global Function in JS.

By the way, this isn't considered great practice for security reasons. I'm curious as to why you might be looking to do this as there might be a better solution.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval

console.log(eval('2 + 2'));
console.log(eval('"Hello" + " " + "World"'));

I hope this answers your question!

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.