Karthikeyan
Karthikeyan

Reputation: 414

JavaScript - Creating function object from function definition in a String

In JavaScript, is there any way to create function object from function definition in a String?

Something similar to a JSON.parse for creating JSON from a String.

const parseFunction = (str)=> {
   // What should be implemented here?
   return func;
}
let funStr = parseFunction("function replacer(arg1) {console.log(arg1)}");

Upvotes: 1

Views: 79

Answers (2)

Karthikeyan
Karthikeyan

Reputation: 414

Just improvising Mr.@abhishek-sharma answer,

The function created using Function('"use strict";return (' + str + ')')(); will not be closure of current scope. In case if anyone want to access some variable in the current scope,

const parseFunction = (str) => {
  return Function(
    'varNameInStr',
    'return function() {return (' + str + ')}',
  )(varInCurrScope)();
};
parseFunction("function(){console.log(varNameInStr)}")

Upvotes: 1

Abhishek Sharma
Abhishek Sharma

Reputation: 3310

Using eval invites a lot of security risks in your application. Javascript now has a alternative to that here

const parseFunction = (str)=> {
   return Function('"use strict";return (' + str + ')')();
}
let funStr = parseFunction("function(arg1) {console.log(arg1)}");

You try playing around it this is just for reference.

Upvotes: 1

Related Questions