0

I'm trying to make my own eval function in JavaScript, which will execute a string in the surrounding context, like eval, plus add a few more things.

So, in general, when doing:

eval("var foo = 8");
foo; // === 8

No problem; however, when I want to extend eval with my own function, like so:

function myEval(str) {
    return eval(str);
}
myEval("var foo = 8");
foo; //error, "foo" is not defined etc.....

And the obvious reason is because in myEval, the eval function called is only executed in that function's scope, not the surrounding scope.

I was wondering if its possible to execute eval in the scope it's surrounding function was called, in order to extend the JavaScript function eval?

1 Answers1

-1

Figured it out, just wrap the eval function in another function, and call that other function in the surrounding scope, like so:

function g(str) {
    return {
        eval,
        go(){
            this.eval(`
              //some other cool stuff
              let test = 1000;
              ${this.str}
            `)
        },
        str
    }
}
g("var pp = 3 * test").go()
console.log(pp);

EDIT:

this actually accomplishes it:

function str(cod1,cod2) {
    return `
        ${cod1};
        (function(...args) {
            ${cod2}
        })
    `
}

function scope1() {
  eval(str(
    `
      var x,
          y,
          z
    `,
    `
      x = args[0];
      y = args[1];
      z = args[2];

    `
  ))(1, {test(){return "ing"}}, {ok:"string"})
  console.log(x,y.test(),z, "scope1");
}

scope1();

try {
  console.log(x, y, z);
} catch(e) {
  console.log(e.toString());
}