Search code examples
javascriptarraylistinstanceevalnodelist

eval template string and class instances


During a code refactoring exercise, eval() was put into service to parse a template string and instantiate a class. The running code is linked to below.

 eval(`let ${tempid} = new Accordian(${"[j]"})`)

Why does this string appear to need quotes around the object referenced by [j] to work?

My other question has to do with class instances, and whether they've been created?

So, the variable tempid is supposed to be a string extracted from a nodeList, but the error I'm getting seems to suggest otherwise, despite the fact the code runs which, to my mind, it wouldn't do unless it has actually instantiated a new class for each of the accordian objects extracted as unique from the markup.

Have two new class instances been created?

I'm getting the following errors:

 'Accordian' is defined but never used. (no-unused-vars) eslint

 'use strict' is unnecessary inside of modules. (strict) eslint

 eval can be harmful. (no-eval) eslint

https://codesandbox.io/embed/eager-morning-9s5ti?fontsize=14

Edit eager-morning-9s5ti


Solution

  • Why quotes?

    "[j]" is the String inserted into the template string by ${ }. As far as I can tell, the whole ${"[j]"} part could just be replaced with [j].

    "Accordian never used"

    Your linter doesn't know what eval will do at runtime. Since you're only using Accordian in a string, it's not actually used in your code.

    "eval can be harmful"

    eval is evil. Depending on the value of the inserted tempid, the evaluated string could contain arbitrary (potentially harmful) code. You might wanna use tempid to set an attribute on some object instead, e.g. global[tempid] = new Accordian([j]). This would let the linter see the class' usage as well.