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.

Micah
  • 4,254
  • 8
  • 30
  • 38

2 Answers2

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.

Ze'ev G
  • 1,646
  • 2
  • 12
  • 15
1
var a = eval (" return function() { alert('yo')}; ");

But don't

Tom
  • 43,583
  • 4
  • 41
  • 61