On dynamic property of JavaScript is that "eval" changes the calling context. What does it mean? Some examples would be better.
3 Answers
eval does change the context when called indirectly. And it changes it to the global context (the default context for all functions).
var myObj = { a: 1 }
function someFunc() {
console.log(eval('this.a')) // 1
console.log(eval('this === myObj')) // true
var indirectEval = eval
console.log(indirectEval('this.a')) // undefined
console.log(indirectEval('this === window')) // true
}
void someFunc.call(myObj)
Direct eval calls don't change the context (nor do they change the scope).
See “Global eval. What are the options?” for details.
Comments
The "a" variable is part of the context, and the eval changes it.
The calling context is the variables that surround the eval call, in our case just the "a" variable and "this" that in the browser equals the window.
var a = 1;
eval("a = 2;");
alert(a); // 2
An example that is more clear http://jsfiddle.net/9h6n7/2/ :
function executeEval(){
eval("a = 2;");
}
var a = 1;
executeEval();
alert(a); // 2
2 Comments
I assume you mean the execution context, not the calling context.
Explaining it here doesn't seem to make much sense, since there are many online articles dealing with this and good JS books such as Javascript, The Good Parts also deal with it.
Here's a link which came top in Google: http://ajax.sys-con.com/node/676031
evalscopes to the calling context. See this for some code. It means the context in whichevalis called is the context that the code being evaluated will execute in.