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.

10
  • 3
    var string = () => this.count++;var func1 = {}; func1['f'] = string(); Commented Jun 24, 2016 at 10:45
  • Are you asking how to create a function for later execution based on code in a string? What is the context of "this" ? Commented Jun 24, 2016 at 10:45
  • @AlexK. actually this have no context.. I need to save it in an object.. in that object this have a context Commented Jun 24, 2016 at 10:46
  • 1
    Why do you think you need to do this? Because you almost certainly don't. Commented Jun 24, 2016 at 10:47
  • 1
    @PranavCBalan thanks it works on chrome Commented Jun 24, 2016 at 10:53

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.