Specify scope for eval() in JavaScript?

后端 未结 9 1263
心在旅途
心在旅途 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:51

    The poor man's method:

    If your scope is not too dynamic, just a couple of static and read-only declarations, simply put it in a string and concatenate with the string what you wanna execute like this:

      const scopeAll = `
        const myFunc = (a, b) => a + b + s; 
      `
    
      const scope1  = `
        ${scopeAll}
        const s = 'c';
      `
      const scope2  = `
        ${scopeAll}
        const s = 'd';
      `
      
      const myStringToExecute = `
        myFunc('a', 'b')
      `
      
      
      console.log(eval(scope1 + myStringToExecute));
      console.log(eval(scope2 + myStringToExecute));

提交回复
热议问题