Specify scope for eval() in JavaScript?

后端 未结 9 1280
心在旅途
心在旅途 2020-11-27 07:24

is there any way I can execute eval() on a specific scope (but NOT global)?

for example, the following code doesn\'t work (a is undefined on the sec

9条回答
  •  Happy的楠姐
    2020-11-27 07:44

    Simple as pie.

    // Courtesy of Hypersoft-Systems: U.-S.-A.
    function scopeEval(scope, script) {
      return Function('"use strict";return (' + script + ')').bind(scope)();
    }
    
    scopeEval(document, 'alert(this)');

提交回复
热议问题