问题
ECMA-262 5.1 subsections 10.4.2 and 10.4.2.1 refer to a "calling context." This doesn't appear to be described anywhere else in the document.
Quoting the spec, emphasis mine:
10.4.2 Entering Eval Code
The following steps are performed when control enters the execution context for eval code:
- If there is no calling context or if the eval code is not being evaluated by a direct call (15.1.2.1.1) to the eval function then,
10.4.2.1 Strict Mode Restrictions
The eval code cannot instantiate variable or function bindings in the variable environment of the calling context that invoked the eval if either the code of the calling context or the eval code is strict code. Instead such bindings are instantiated in a new VariableEnvironment that is only accessible to the eval code.
What does "calling context" mean in these paragraphs? I would assume it refers to the Execution Context at the top of the stack just before
eval
is called; can anyone verify this?What does it mean to have "no calling context?" Can someone provide an example of code or conditions that could result in a call to
eval
with no calling context?
回答1:
The "calling context" refers to the context which the native eval
function is being called from.
If you are executing eval
from some native code (for example, you run a native function which executes code when completed using eval
for some reason or another), then it would have no context, which is then specified to run under the global scope. The context only refers to ECMAScript executable code.
However, the calling context refers to the variables and directives in the execution context of where it is called. For example, it only knows that eval is meant to work as strict code if it checks the calling context.
This is clarified by a very similar question in the ES-Discuss mailing list, where Brendan Eich (the creator of JavaScript) responds:
How can eval code not have a calling context?
ES3 says:
10.2.2 Eval Code
When control enters an execution context for eval code, the previous active execution context, referred to as the calling context, is used to determine the scope chain, the variable object, and the this value. If there is no calling context, then initialising the scope chain, variable instantiation, and determination of the this value are performed just as for global code.
I am baffled by "If there is no calling context". How could the possibility arise? How would
eval
get called if no one calls it?
Response:
A call from native code, the "host" program.
Some browsers support indirect
eval
, allowing this:setTimeout(eval, 0, "alert('hi mom')");
The window used is the one in which
setTimeout
was found along the scope chain, somyFrame.setTimeout(eval, 0, "alert(x)");
should show
myFrame.x
, not the calling frame or window'sx
.
Note: myFrame
in this instance refers to the frame's global scope.
来源:https://stackoverflow.com/questions/21059056/what-is-a-calling-context