js,将字符串转换为函数 [英] js, turn string to function
问题描述
我想知道如何将字符串转换为包装函数。
我有一个字符串函数数据
var a = new String(alert(turned));
我想将a变成一个包装函数
a = function(){a}; //失败
a = function(){eval(a)}; //失败
var b = a;
$ ba = function(){eval(b)} //成功
我想知道人们通常会做什么来将其转换为包装函数。
非常感谢您的建议。
您也可以像这样使用带有 new
关键字的函数构造函数。
var a = new String(alert('hello'));
a = new函数(a)
a()
会导致警报'hello'
你甚至可以使用这个接受参数的方法创建一个新的函数。请参阅 https://developer.mozilla.org/en-US / docs / JavaScript / Reference / Global_Objects / Function
但是我会小心你变成一个函数。您不希望用户能够执行代码。
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.
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.
这篇关于js,将字符串转换为函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!