评估模板字符串和 class 个实例

eval template string and class instances

在代码重构练习中,eval() 投入使用以解析模板字符串并实例化 class。 运行 代码链接到下面。

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

为什么这个字符串似乎需要在 [j] 引用的对象周围加上引号才能工作?

我的另一个问题与 class 个实例有关,它们是否已经创建?

所以,变量 tempid 应该是从 nodeList 中提取的字符串,但我得到的错误似乎暗示并非如此,尽管事实上代码运行在我看来是行不通的除非它实际上已经为每个从标记中提取为唯一的 accordian 对象实例化了一个新的 class。

是否创建了两个新的 class 实例?

我收到以下错误:

 '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

为什么要加引号?

"[j]"${}插入到模板字符串中的String。据我所知,整个 ${"[j]"} 部分可以替换为 [j].

"Accordian never used"

您的 linter 不知道 eval 在运行时会做什么。由于您仅在字符串中使用 Accordian,因此它实际上并未在您的代码中使用。

"eval can be harmful"

eval是邪恶的。根据插入的 tempid 的值,评估的字符串可能包含任意(可能有害的)代码。您可能想使用 tempid 来设置某个对象的属性,例如global[tempid] = new Accordian([j])。这也会让 linter 看到 class' 的用法。