On Thu, 02 Oct 2008 11:19:26 -0700, Bruce wrote:
Are you *sure* this is a good idea?
eval("x = 5");
Eval is very seldom the correct tool to use.
>
For reasons that are too long to explain, I can't do this
eval("window.x = 5");
If you *must* use eval, why can you not:
{ eval("x = 5"); window.x = x; }
Any thoughts on how I can do this within the scope of a Class? I know
this is non standard and might seem odd or inadvisable but it's a long
story that will be solved if someone can help with my problem.
Tested in Fx 3.0.2, IE6 and Opera (something)
<html>
<head>
<title>Test</title>
</head>
<body>
<script type="text/javascript">
function w(s)
{
document.write(s + "<br>");
}
var _global = (function() {return this})();
var x = 10;
(function() {
var x = 5;
w("Anon function start");
w("Inner: x= " + x);
w("_global.x= " + _global.x);
w("Showing we don't get a primitive reference");
x = _global.x; // This makes a COPY of _global.x
x = 8; // And this line doesn't affect global x at all
w("Inner: x= " + x);
w("_global.x= " + _global.x);
w("Anon function inside an anon function finds the 'closest' x");
(function() { // Even in a new scope, it will find "inner_x" first.
x = 18;
})();
w("Inner: x= " + x);
w("_global.x= " + _global.x);
w("As does eval");
eval("x = 22");
w("Inner: x= " + x);
w("_global.x= " + _global.x);
// Note: I CANNOT actually recommend that someone USE this method.
// The use of "with" is considered evil by many for very good reason.
// If this is the "solution" to a problem, I'm willing to wager you
have
// have far bigger problems.
//
// "with" is considered bad form by many. Don't do it.
w("But the WITH statement is ... magic");
with(_global) {
x = 15;
}
w("Inner: x= " + x);
w("_global.x= " + _global.x);
w("But the WITH statement is ... magic -- with eval");
with(_global) {
eval("x = 25");
}
w("Inner: x= " + x);
w("_global.x= " + _global.x);
})();
w("And the end, we have: global x= " + x);
</script>
</body>
</html>