0

I want to know how can i turn string into a wrap function.

I have a string function data

var a = new String("alert(turned)");

And I want to turn a into a wrapped function

a = function(){ a }; // failed

a = function(){ eval(a) };  // failed

var b = a;

a = function(){ eval(b) } // success

I want to know what do people will do in general to turn a into a wrapped function.

Thank you very much for your advice.

2 Answers 2

3

You can also use the function constructor with the new keyword like this.

var a = new String("alert('hello')");
a = new Function(a)
a()

Would result in an alert box with 'hello'

You can even make a new function using this method which accepts arguments. see here https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function

But I would be careful about what you turn into a function. You don't want users to be able to execute code.

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

Comments

1
var a = eval (" return function() { alert('yo')}; ");

But don't

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.