0

I heard that use eval function in JavaScript is bad idea but I have this code:

// this string (function)  is generated dynamically...
var funVal = 'alert("a")' ;        
//.....

var Button1 = document.getElementById("BtnSave");
// onclick event of button
eval("Button1.onclick = function () { " + funVal + " };");  

I don't want to use eval. Is there another solution?

David G
  • 94,763
  • 41
  • 167
  • 253

3 Answers3

5

Just write very nearly that code without eval, there's nothing there that needs it:

var funVal = function() {
    alert("a");
};

var Button1 = document.getElementById("BtnSave");
Button1.onclick = funVal;

In the comments you've said that the code is dynamically-generated server-side. That's not a problem at all, just have the server output the code where JavaScript code is expected (inside <script>...</script> tags, or as the full content of a response you'll load via <script src="..."></script>). The key in either case is to make sure that what you send to the browser is valid code.

Example 1: Dynamically-generated inline script tag (you haven't said what the server-side technology is, so I went with the fairly-common PHP):

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Inline Dynamically Generated Script</title>
</head>
<body>
<p>Each time you load this page, the script in the inline
<code>script</code> tag at the end is different.</p>
<button id="theButton">Click Me</button>
<script>
document.getElementById("theButton").onclick = function() {
    alert("<?php echo("Hi there, this page's magic number is " . rand(0, 10000)); ?>");
};
</script>
</body>
</html>

Live Example

Example 2: Dynamically-generated script in separate file:

HTML:

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Dynamically Generated Script from File</title>
</head>
<body>
<p>Each time you load this page, the script in the file
loaded by the <code>script</code> tag at the end
is different.</p>
<button id="theButton">Click Me</button>
<script src="dynamic-script.php"></script>
</body>
</html>

JavaScript file (dynamic-script.php):

<?php header('Content-type: application/javascript'); ?>
document.getElementById("theButton").onclick = function() {
    alert("<?php echo("Hi there, this page's magic number is " . rand(0, 10000)); ?>");
};

Live Example

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • thanks for your anwer but... "alert ('a') " is just one example, the code is generated dynamically on server side – CSPHPJAVA SQLAJAX HTMLJS Dec 21 '12 at 23:25
  • @CSPHPJAVASQLAJAXHTMLJS Having JS code generated by another system is one of the few cases where you have to use eval, because there is no other way to pass a function from one system to another except for doing it in sourcecode form. But why do you create JS code on a server in the first place? This really seems strange to me. – Philipp Dec 21 '12 at 23:28
  • @CSPHPJAVASQLAJAXHTMLJS - generating code on the server without eval is no problem at all if you're doing it at page generation time. You just put the generated function into ` – jfriend00 Dec 22 '12 at 00:12
  • @CSPHPJAVASQLAJAXHTMLJS: I can only echo jfriend00 above, it's fine that it's generated server-side. The code gets sent to the browser as text anyway. The browser then interprets the text it receives (either the text between script tags or the text of an entire file if you use ). I've updated the answer with examples of doing that. – T.J. Crowder Dec 22 '12 at 07:16
0

I don't know why you're doing this, but a better way would be to use the Function constructor:

new Function("Button1.onclick = function () { " + funVal + " };")();

But you don't have to use this or the eval solution. Doing this is exactly equivalent in output:

Button1.onclick = function() { alert('a'); };
David G
  • 94,763
  • 41
  • 167
  • 253
  • using `x = new Function ()` is considered bad practice. In most cases you should rather use `x = function() { }`. See this question for details: http://stackoverflow.com/questions/3026089/legitimate-uses-of-the-function-constructor – Philipp Dec 21 '12 at 23:25
  • Bad practice? You mean in this case worse than `eval`? – David G Dec 21 '12 at 23:26
  • No, but it's still not nearly as good as function(). I think I should have pointed that out, because you didn't really make that very clear. – Philipp Dec 21 '12 at 23:33
0

Javascript allows you to treat functions like variables. You can assign them to other variables, you can pass them to other functions as arguments, and you can even have functions which return other functions. This can be used in most situations where you would use evil()eval().

Philipp
  • 67,764
  • 9
  • 118
  • 153