Using eval () with a custom global

Is it possible to specify which object to use for global when calling eval() ?

(I am not asking how to make global eval ().)

This does not work, but it illustrates what I would like:

 var pseudoGlobal = {}; eval("x = 12", pseudoGlobal); pseudoGlobal.x; // 12 

The fact is that real global bindings are not affected by the declaration of an implicit variable (i.e. without var ) in the eval () 'ed code.

Regarding eval.call(pseudoGlobal, "x=12") or eval.apply(pseudoGlobal, ["x=12"]) , some interpreters will not allow this.

+6
source share
2 answers

You can, of course, replace the default object to assign a property value, for example, to

 with (pseudoGlobal) eval("x=12") 

but not for creating a property. If the property is not found in the current stack of execution contexts, it is created in the global object. That is all there is. You can try some weird things as well:

 //global code var globalvars = {}; for (i in this) globalvars[i] = null; with (pseudoGlobal) eval("x=12") for (i in this) if (!(i in globalvars)) { pseudoGlobal[i] = this[i]; delete this[i]; } 

If you need global bindings, try:

 var globalvars = {}; for (i in this) globalvars[i] = this[i]; with (globalvars) eval("x=12") 

this way the bindings will be changed in globalvars. Please note that this shallow copy will prevent only one beat level from changing.

+3
source

There is no built-in way to do this.

Two solutions come to mind:

  • The prefix of all assignments in eval ed code. those. instead of x = 12 , you need to do something like ox = 12 .
  • Write a custom Javascript interpreter that isolates the script file and returns an object with all the variables assigned.
+1
source

Source: https://habr.com/ru/post/918175/


All Articles