Matthias S Matthias S - 6 months ago 14
Javascript Question

How bad is eval() to read function parameter

I have used Hopscotch to make a guided tour through my Website. Now for that you have to make a JS object which will be the parameter to call the startTour() function which will initiate the Tour.
In this example a tour is started by clicking a a.hopscotch-start link.

HTML:

<a href="#" class="hopscotch-start" data-name="x">Start tour</a>


JS:

var x = {id: "tour1", steps: [{title: "the title",....}]};
$("a.hopscotch-start").click(function (e) {
e.preventDefault();
hopscotch.startTour(eval($(this).data('name'))); // -> startTour(x);
return false;
}


How bad is this actually? I know that eval is "slow", but it would give me the flexibility to have just one general click code and not bother about it any more. What is the actual security risk, if any? And does that significantly slower the code (regarding the fact that the code is just reading a string to be parsed as a variable).

Thank you for your feedback - any other solution than eval to achieve the same is also welcome.

Answer

Why not make an object and get it by keys? It will be quicker and safer:

var tours = {
  x: {id: "tour1", steps: [{title: "the title",....}]},
  y: {id: "tour2", steps: [{title: "the title",....}]}
}
$("a.hopscotch-start").click(function (e) {
  e.preventDefault();
  hopscotch.startTour(tours[$(this).data('name')]); // -> startTour(x);
  return false;
}
Comments