Search code examples
javascripteval

javascript eval in context without using this keyword


I am trying to execute eval within a particular context. I have found the answer here useful. However I am getting the following behavior in Chrome Version 53.0.2785.143 m. Not tried other browsers. The code I am using is the following:

function evalInContext(js, context) {
    return function() { return eval(js); }.call(context);
}


console.log(evalInContext('x==3', { x : 3})) // Throws
console.log(evalInContext('this.x==3', { x : 3})) // OK

However I expected the first call to evalInContext not to throw. Any ideas why this might be happening?


Solution

  • Scope and Context are not the same

    The way variable x is resolved has nothing to do with context. It is resolved by scope rules: does any of the closures define that variable? If not, look in the global object. At no point the variable is resolved by looking in the context.

    You could have a look at this article.

    The behaviour is not particular to eval, it is the same with other functions:

    "use strict";
    
    var obj = { x : 3};
    var y = 4;
    
    function test() {
      console.log(this.x); // 3
      console.log(typeof x); // undefined
    }
    
    test.call(obj);
    
    function test2() {
      console.log(this.y); // 4
      console.log(typeof y); // number
    }
    
    test2.call(window);