0

I am facing one scenario as below,

function a() {
  var $$ = this;
  eval("some script");
}

using closure compiler with simple level, it will remove the $$ var in the simplified output, but this variable maybe used by the code "some script" from script developers, so is there anyway to let closure compiler keep var $$ in the output? Thanks!

John
  • 5,443
  • 15
  • 21
Joey Sun
  • 109
  • 3
  • 8
  • Possible duplicate of [Google Closure Compiler - How to create an Extern for a variable (variable name can't change as it is in an Eval)](https://stackoverflow.com/questions/33135183/google-closure-compiler-how-to-create-an-extern-for-a-variable-variable-name) – Chad Killingsworth Oct 22 '18 at 12:04

3 Answers3

2

Borrowing from Solution: Export the Symbols You Want to Keep I suggest you use a bracket notation to create this var. I'm assuming that your global element is window.

function a() { window['$$'] = this; eval("some script"); }

It might not be pretty, but this does work;

With an output of

function a() { window.$$ = this; eval("some script"); }

Graham P Heath
  • 7,009
  • 3
  • 31
  • 45
0

No not really. You might be able to find a workaround, but it's not guaranteed to work in future compiler versions.

You would need to rework you code not to utilize eval like that.

Chad Killingsworth
  • 14,360
  • 2
  • 34
  • 57
0

Use the Function constructor:

var a = new Function('var $$ = this; eval("some script");');

If you want to avoid escaping the contents of "some script", you can pass it in as parameter:

var a = new Function('script', 'var $$ = this; eval(script);');

This keeps needed locals out of the compiler's analysis.

John
  • 5,443
  • 15
  • 21