function fun(){
eval("var key = 'value';");
return key;
}
fun() //returns 'value' as expected
However, when I use eval inside a method in a class, I get a Reference Error, as shown below:
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
I understand eval should be avoided, nevertheless like to understand this behavior.