Fwd: Indirect references to variables

Bergi a.d.bergi at web.de
Wed Dec 9 05:21:26 UTC 2015


John Gardner schrieb:
> ECMAScript currently offers no clean way to "dereference" a variable in the
> current scope.

There is one. It's called `eval`.

> A hacky workaround is to create an anonymous function that simply returns a
> reference to the named variable:
>
>      function dereference(name){
>          return new Function([], "return " + name)();
>      }
>      dereference("Paintbrush") === Paintbrush; // true

Actually that does only work with global variables as well, quite like 
the property access on the global object.

> Another approach
> might be to leverage `eval`, which opens up the obvious issues of
> performance and security.

And so does your proposed backslash operator.
The only difference I can see would be that you are wishing to 
`eval`uate only identifier references not arbitrary expressions, but 
*that* can be trivially dealt with by testing the expression to match 
the Identifer production. A regex could do that.
Neither performance nor security would be any better though.

The preferred way of what you are trying to do is to whitelist the 
classes you want to make available, and by naming/aliasing them 
explicitly. Basically

     var classReference = {Paintbrush, …}[className];
     var instance = new classReference();

For additional security, you might want to use an object that doesn't 
inherit from `Object.prototype`, or just a `Map` right away.

Regards,
  Bergi


More information about the es-discuss mailing list