Specify scope for eval() in JavaScript?

后端 未结 9 1307
心在旅途
心在旅途 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条回答
  •  甜味超标
    2020-11-27 07:45

    This worked for me the best:

    const scopedEval = (scope, script) => Function(`"use strict"; ${script}`).bind(scope)();
    

    Usage:

    scopedEval({a:1,b:2},"return this.a+this.b")
    

提交回复
热议问题