global.a = 20; var a = 10; { let a = {}; eval('a.member = 5'); } 

Eval will add a property to object a in the same block? Or global? The main question is that if several asynchronous functions call such an eval, will they not work with the same global variable?

  • global.a = 20; var a = 10; is this node.js? - Qwertiy
  • @Qwertiy yes it's him - manking
  • Then global is global. In var, the scope is a module. - Qwertiy

1 answer 1

https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/eval

  • The direct call to eval is local (with some reservations).
  • Indirect in ES5 + - global.
  • Indirect in ES3 - any behavior, including throwing an exception.

 var x = {}; { let x = {}; // локальный скоуп eval("xa = 1"); (eval)("xb = 2"); // глобальный скоуп (1,eval)("xk = 16"); window.eval("xl = 17"); const e = eval; e("xm = 18"); [eval][0]("xn = 19"); eval.call(null, "xo = 20"); console.log(x); } console.log(x); 
 .as-console-wrapper.as-console-wrapper { max-height: 100vh } 

Specifications about the local scope:

  • Variables declared inside eval via let and const do not appear in the current scop.
  • Variables declared inside eval through var , as well as functions declared via function declaration, appear in the current mode only in lax mode.

 ~function () { eval("var a = 1"); eval("let b = 2"); eval("const c = 3"); eval("function d() {}"); console.log(typeof a, typeof b, typeof c, typeof d); }(); ~function () { 'use strict'; eval("var a = 1"); eval("let b = 2"); eval("const c = 3"); eval("function d() {}"); console.log(typeof a, typeof b, typeof c, typeof d); }(); 

  • And what is meant by "Direct call eval - in the local (with some reservations)." What reservations? - manking
  • one
    @manking, already added. - Qwertiy
  • @manking, and more added. - Qwertiy
  • About let is strange. It turns out when eval is called, then it kind of creates a block {} within which it calls the code? - manking
  • one
    @manking, well, roughly so to speak. But pay attention to var in strict mode - its behavior is not explained by the block. Although you can try to say a block type in a non-strict and self-invoking function (although this and arguments are hardly possible) in a strict one. But in general, I suspect that it is not so. In general, it is better not to subtilize with generalizations. - Qwertiy