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?

13
  • Why are you using this function at all? It looks like a long-winded, dangerous, and inefficient way to write: context[scr] Commented Aug 5, 2018 at 21:34
  • Apologies, that function was taken from the linked SO post as an example of how to refer to dog without doing this.dog when using eval in a particular context. I'm not using that function. Commented Aug 5, 2018 at 21:38
  • I still don't understand the problem you are trying to solve with eval Commented Aug 5, 2018 at 21:41
  • Please elaborate. context[scr] does respond to your "if I have an object... then I'd be able to ... without this.dog". So what is the problem? Commented Aug 5, 2018 at 21:41
  • 1
    @Roymunson - That doesn't really clarify things. Why are you evaling code in the first place? eval is even more discouraged that with. Commented Aug 5, 2018 at 21:44

1 Answer 1

1

is there an alternative solution?

Sure but thats way worse than with :

 return new Function(...Object.keys(context), scr)(...Object.values(context));
Sign up to request clarification or add additional context in comments.

2 Comments

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?
@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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.