0

I have some JavaScript function definitions stored in a string.

"function firstFun() {
  return 'some text';
}

function secondFun() {
  console.log(firstFun())
}"

Is it possible to access and call these functions like any other function? Like:

var text = firstFun(); // return 'some text'
secondFun();           // print 'some text'
2
  • 3
    You could (but should not) use eval or parse the string by yourself. However, I would strongly recommend to reconsider your design. Commented Aug 6, 2018 at 11:19
  • 3
    It's possible, but should be avoided in almost all situations. Which problem should 'creating functions from strings' solve? Commented Aug 6, 2018 at 11:19

2 Answers 2

4

If you have stored JS code in string, you'll have to eval it (which is a dangerous operation - if you're running untrusted code as T.J. Crowder clarified):

const code = `
  function firstFun() {
    return 'some text';
  }

  function secondFun() {
    console.log(firstFun())
  }
`;

eval(code);
Sign up to request clarification or add additional context in comments.

4 Comments

"which is a dangerous operation" Only if the content you're evaling is from an untrusted source.
After I evaled how should I call the function? I tried the default way like I stated in my question, but I get an exception that "firstFun is not defined".
firstFun should be available in the context.
If anyone got the exception I had, maybe you're using strict mode and that's why it fails.
0

Various ways ... even depending if you can change the format of the strings. But this should give you an idea. Keep in mind, that this can be dangerous, if you add such functionality to your scripts.

With eval:

const code = `
  function firstFun() {
    return 'some text';
  }

  function secondFun() {
    console.log(firstFun())
  }
`;

eval(code);
secondFun();

Putting it in a script tag:

const code = `
  function firstFun() {
    return 'some text';
  }

  function secondFun() {
    console.log(firstFun())
  }
`;

var head = document.querySelector('head');
var script = document.createElement('script');
script.type = 'text/javascript';
script.innerHTML = code;
head.appendChild(script);

secondFun();

Use Function constructor:

const firstStr = `return 'some text';`;
const secondStr = `console.log(firstFun())`;

var firstFun = new Function(firstStr);
var secondFun = new Function(secondStr);

secondFun();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.