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?