0

I have a string in Javascript. What I need is to save it as code:

var string = "this.count++";
var func1 = {};
func1['f'] = string; // should be saved as executable code..

How can I do? I don't need eval(), cause I don't need to evaluate in this moment.

granmirupa
  • 2,780
  • 16
  • 27

2 Answers2

3

try

new Function(string)

for example

var string = "this.count++; console.log(1)";
new Function(string)();

Note: Using Function constructor (as with eval) you will be able to execute any arbitrary code which could be a security risk if it contains user-derived text. Not so much an issue if it's definitely the current user who entered it (they have other ways of running code on the page), but if you're running text from User A as code on User B's browser, that's a massive no-no.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
1

You could create new Function() object. Keep in mind that you should avoid this as much as possible, because new Function() and eval() are dangerous!

func1['f'] = new Function(string).

You can read about this more here.

Community
  • 1
  • 1
Patryk Perduta
  • 366
  • 1
  • 2
  • 9