J
jdc_1040
Could someone explain what the scope chain looks like to code running
inside eval? (Please no "eval is the devil" essays ) Let's say I
have a string of JavaScript that looks like this:
var myVar1 = 1;
var myVar2 = 3;
window.someFunc = function() { myVar1++; alertFunc(); };
function anotherFunc() { myVar2++; alertFunc(); }
function alertFunc() { alert(myVar1 + ' ' + myVar2); }
If I run that through eval (from within another function), I can then
do this:
window.someFunc();
and it'll show 1, then 2, then 3, etc. as I call it multiple times. So
I know that myVar1 is hanging around in memory somewhere along with
alertFunc. I know it's not attached to window, since
window.anotherFunc() gives me a standard "undefined" error.
I've also tried doing the eval like this:
function myFunction() { window.someObj = eval(theString); }
I was told this would attach the stuff defined in theString to someObj,
but window.someObj.someFunc is still undefined.
So what I'm wondering is, where are the variables and functions I
didn't explicitly assign to window defined? I've looked at the very
excellent FAQ article regarding scope chains and closures, but it
didn't cover what happens inside eval. Anyone know? Thanks in advance
for any insight.
inside eval? (Please no "eval is the devil" essays ) Let's say I
have a string of JavaScript that looks like this:
var myVar1 = 1;
var myVar2 = 3;
window.someFunc = function() { myVar1++; alertFunc(); };
function anotherFunc() { myVar2++; alertFunc(); }
function alertFunc() { alert(myVar1 + ' ' + myVar2); }
If I run that through eval (from within another function), I can then
do this:
window.someFunc();
and it'll show 1, then 2, then 3, etc. as I call it multiple times. So
I know that myVar1 is hanging around in memory somewhere along with
alertFunc. I know it's not attached to window, since
window.anotherFunc() gives me a standard "undefined" error.
I've also tried doing the eval like this:
function myFunction() { window.someObj = eval(theString); }
I was told this would attach the stuff defined in theString to someObj,
but window.someObj.someFunc is still undefined.
So what I'm wondering is, where are the variables and functions I
didn't explicitly assign to window defined? I've looked at the very
excellent FAQ article regarding scope chains and closures, but it
didn't cover what happens inside eval. Anyone know? Thanks in advance
for any insight.