zimki | all bloggers | admin login | recent entries for Tom Insam
 
JavaScript eval

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

comments:

Martin

on Fri Aug 18 2006 08:24:47 GMT+0100 (GMT)

hi. nice article.

Alternative:
To evaluate code into the 'global' scope:
window.eval(code);

Tom

on Fri Aug 18 2006 11:04:04 GMT+0100 (GMT)

You missed the first paragraph. Spidermonkey doesn't have a window object by default, you have to make one yourself. Web browsers, of course, are a different matter.

Michael

on Sun Aug 26 2007 16:31:25 GMT+0100 (GMT)

Bravo,

This is exactly what I was looking for, my eval() calls were misbehaving!!!

Cheers!

Jason Miller

on Wed Sep 26 2007 06:22:08 GMT+0100 (GMT)

Hmmm.

window.eval() is a step in the right direction for a large project I am working on. Where it falters is when assigning and retrieving variables.

Does anyone know of a way to have variables remain global using eval or document.write(

Mason

on Sat Oct 20 2007 04:05:48 GMT+0100 (GMT)

function geval(code){
if(!!window.execScript){
window.execScript(code); // eval in global scope for IE
return null; // execScript doesn’t return anything
}else if(!!window.eval){
return window.eval(code);
}else{
var dj_global = this; // global scope reference
return !!dj_global.eval ? dj_global.eval(code) : eval(code);
}
}

But Windows Safari does not seem to have any global scope for eval....

leave a comment

name
email
comment