2

People say that Eval brings dynamic scope into JavaScript, but I don't see how that statement is valid. Using Eval evaluates the expression using the same lexical environment/variable environment as the calling environment (reference ECMA 262 v. 5). The Assignment or declaration of the expression is obviously dynamic, but I don't think it is valid to say that it introduces dynamic scope.

Am I right in saying that Eval doesn't introduce dynamic scope?

Community
  • 1
  • 1
contactmatt
  • 18,116
  • 40
  • 128
  • 186
  • No, I think you're wrong. Compare it to `new Function()` which does not execute in the current scope – Andy Ray Feb 26 '13 at 05:44

1 Answers1

1

Yes and no.

In a strict sense, no; the language still operates lexically (except with respect to this, which is always dynamically scoped).

However, if you read the whole question you linked to, you'll see that the asker is using eval to emulate dynamic scope.

var x = 1;

function g() {
    print(x);
    x = 2;
}

function f() {
    // create a new local copy of `g` bound to the current scope
    // explicitly assign it to a variable since functions can be unnamed
    // place this code in the beginning of the function - manual hoisting
    var g = eval(String(g));
    var x = 3;
    g();
}

f();                         // prints 3

print(x);                    // prints 1

Emulating dynamic scope is totally achievable the way that the asker of that question is using it. The asker is using eval to actually import an externally defined function into the scope of another function. This requires stringifying the function and redeclaring it. So the externally defined function isn't really being run within the scope of another function (this example doesn't really demonstrate dynamic scope in a strict sense) because a whole new function is declared. That being said, the asker's intention is to emulate dynamic scope, and he is achieving that with eval.

Community
  • 1
  • 1
Nathan Wall
  • 10,530
  • 4
  • 24
  • 47