0

This post provides a solution for how to use eval within a particular context/scope without having to preface all variables/functions in the eval'd code with this. javascript eval in context without using this keyword

To clarify - let's say I have the following object as the context for an eval statement {dog: "labrador"}. I'd like console.log(eval(dog)) to output "labrador" without having to type eval(this.dog)

However, the solution in the linked post:

function evalInContext(scr, context)
{
    // execute script in private context
    return (new Function( "with(this) { return " + scr + "}")).call(context);
}

uses the with statement. Considering usage of the with statement is discouraged, is there an alternative solution?

Foobar
  • 7,458
  • 16
  • 81
  • 161

1 Answers1

1

is there an alternative solution?

Sure but thats way worse than with :

 return new Function(...Object.keys(context), scr)(...Object.values(context));
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • Interesting, how does this work? I understand the `...` is spread notation - but I'm not sure how this expression executes code considering there is no call to `eval`. Also why would this be worse than `with`? – Foobar Aug 06 '18 at 00:11
  • 1
    @roymunson it creates a function with a few parameters and then calls that function passing in the parameters. It is worse than eval as no one will understand it – Jonas Wilms Aug 06 '18 at 09:38