-1

Is it possible to define a function run that acts like this?

    a = run('var x = 100;')
    b = run('console.log(x);') // prints 100
    c = run('y = 1;')
    d = run('console.log(y);') // prints 1

I tried several ways, using apply and passing the same context, binding a context to a function, returning a closure with a recursive call etc. but I can't seem to get anything to work.

2 Answers2

1

Yeah, as MyLibrary says, you probably want eval, if you really want to do this. So:

var run = eval;
a = run('var x = 100;')
b = run('console.log(x);') // prints 100
c = run('y = 1;')
d = run('console.log(y);') // prints 1

would seem to work.

JavaScript allows assigning functions to variables, so you can set the run variable to eval. As far as eval, you may want to learn about it and as you can see from comments, its use in normal function creation is often discouraged.

pacificpelican
  • 363
  • 1
  • 7
0

Are you referring to eval function?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval

MyLibary
  • 1,763
  • 10
  • 17