0

I have been trying to figure this out for a while, and I cannot wrap my head around how to do this. I dynamically created a function composed of different strings, and I would like to be able to turn this into actual javascript that can be called on.

I simplified this example but it still should help solve my problem.

var previewStringFunction = "function updateMap() {"
 + "some javascript code" + "}"
4
  • 1
    Why are you creating a function out of strings? You can eval it but it's bad practice. Commented Mar 4, 2013 at 6:47
  • What is the need to create dynamic function? Commented Mar 4, 2013 at 6:50
  • its part an application that allows people to see the script they are creating and I want to be able to execute it Commented Mar 4, 2013 at 6:51
  • 1
    possible duplicate of Calling a function by a string in JavaScript and staying in scope Commented Mar 4, 2013 at 6:52

2 Answers 2

3

You can use The eval() function for evaluating.

sample:

var strng = "function executeThs(){  alert('hello world'); }";// your string
eval(s);// evaluation of your function
executeThs();// calling function

http://www.w3schools.com/jsref/jsref_eval.ASP

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

Comments

0
<html>
  <head>
    <script language="javascript">
<!--
function foo ()
{
  var script = document.createElement ('script');
  script.innerHTML = "function bar () {alert ('bar');}";
  body.appendChild (script);
}
// -->
    </script>
  </head>
  <body id="body">
    <input type="button" onclick="foo(); return false;" value="foo" />
    <input type="button" onclick="bar(); return false;" value="bar" />
  </body>
</html>

Button foo defines function, button bar calls it.

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.