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.

Dipti Kumari
  • 41
  • 2
  • 9

1 Answers1

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!