Strict mode eval

Lasse Reichstein reichsteinatwork at gmail.com
Tue May 10 12:34:30 PDT 2011


On Tue, 10 May 2011 19:16:40 +0200, Andreas Rossberg <rossberg at google.com>  
wrote:

> I'm a bit puzzled regarding the meaning of "use strict" in the context
> of higher-order uses of eval.
>
> Consider the following program. What is the expected result of the  
> latter calls?
>
> ---------------------
> var x = 3
>
> function call_eval() { x = 3; eval("var x = 4"); return x }
> function call_eval_strict() { "use strict"; x = 3; eval("var x = 4");  
> return x }
>
> function get_eval() { return eval }
> function get_eval_strict() { "use strict"; return eval }

These two, get_eval and get_eval_strict, should be equivalent. They both  
return
the same value, the eval function.

> function call_f(f) { x = 3; f("var x = 4"); return x }
> function call_f_strict(f) { "use strict"; x = 3; f("var x = 4"); return  
> x }
>
> call_eval()  // 4
> call_eval_strict()  // 3

Agree.

>
> call_f(eval)  // 4
> call_f(get_eval())  // 4
> call_f(get_eval_strict())  // ?

All equivalent, they call the same function with the same argument.

> call_f_strict(eval)  // ?
> call_f_strict(get_eval())  // ?
> call_f_strict(get_eval_strict())  // ?

And again equivalent, so the question is what the result is.

The call to f in call_f_strict is an indirect call to eval in a strict
context.
That means that the eval code is not strict code (10.1.1) since it's
not a direct call, and it doesn't contain the "use strict" directive.

I.e., its evaluated as a normal indirect call to eval, which uses the
global environment as VariableEnvironment and LexicalEnvironment, and
the "var x = 4;" will overwrite the global variable x.

I.e., 4 is the correct answer.

> (function() { "use strict"; return call_f_strict(get_eval_strict())  
> })()  // ?

And this is the same (same function called with same argument). That
it happens in a strict environment doesn't change anything.

> ---------------------
>
> V8 bleeding edge currently returns 4 for all of the latter calls, but
> that does not seem quite right to me. Especially for the last two
> cases

Seems this is correct.

> that would practically amount to a loop hole in strict mode. But where
> does the spec say differently?

It's only a loop hole in strict mode if the strict code has access to the
unmodified eval function. You can get out of strict mode too, if you have
access to the original Function constructor.
What you can't do is to execute non-strict code inside a strict-mode  
context.

/L
-- 
Lasse Reichstein Holst Nielsen - reichsteinatwork at gmail.com


More information about the es-discuss mailing list