评估类中的内部方法

时间:2018-08-12 05:45:13

标签: javascript node.js

function fun(){
    eval("var key = 'value';");
    return key;
}

fun() //returns 'value' as expected

但是,当我在类的方法中使用eval时,会出现“引用错误”,如下所示:

class c {
   constructor() {
   }
   funInClass(){
     var key1="value1"
     eval("var key2 = 'value2';");
     console.log(key1);
     console.log(key2);
   }
}

var obj=new c();
obj.funInClass();
value1 //prints as expected
ReferenceError: key2 is not defined  // was expecting eval to have declared/initialized key2

我知道应该避免评估,但是仍然希望了解这种行为。

0 个答案:

没有答案