Tom Insam
on Mon Aug 07 2006 10:37:10 GMT+0100 (GMT)
(First, a note. All this code is based off JavaScript in SpiderMonkey. I
don't know how eval works in Internet Explorer, or any web browser for
that matter. I care about Zimki.)
JavaScript eval is a curious beast. Rather than being a global function,
as I expected, it's an instance method of Object -
Object.prototype.eval. Because there's always a 'this' object, and
function calls in JavaScript are actually just instance calls on this
implicit object, it can often appear as though there's an eval
function. But there isn't, and you can play with this effect.
What the eval method does is evaluate the passed string as JavaScript
in the context of the Object upon which it is
called. With the implicit 'this' form of eval, which is what you mean
most of the time, it'll evaluate the string you pass in the current
context, which tends to be fine. But given some Object, you can evaluate
code into its context easily. An example tends to help here:
var code = "var a = 1";
eval(code); // a is now '1'.
var obj = new Object();
obj.eval(code); // obj.a is now 1
This is especially important if you want to evaluate code inside of a
function:
var a = 2;
function foo() {
eval(code); // a is 1, but scoped inside the function
}
foo();
// a is back to being 2 here
To evaluate code into the 'global' scope, you'll need to take a
reference to it outside the function, and call eval on it:
var a = 2;
var global = this;
function foo() {
global.eval(code); // a is 1 globally now
}
foo();
// a is now 1
|