javascript eval in context without using this keyword

后端 未结 4 1585
逝去的感伤
逝去的感伤 2021-01-14 00:54

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.

4条回答
  •  迷失自我
    2021-01-14 01:15

    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);

提交回复
热议问题