1
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.

Ry-
  • 218,210
  • 55
  • 464
  • 476
Vin Dat
  • 11
  • 3
  • 2
    As soon as you use `class`, you are in "strict mode". See [Indirect eval call in strict mode](//stackoverflow.com/q/19357978) for details on eval in strict mode. – Heretic Monkey Aug 12 '18 at 05:49

0 Answers0