![](/img/trans.png)
[英]Is there a way to create an arrow function from a string with javascript?
[英]Is there a way to create a function from a string with javascript?
例如;
var s = "function test(){
alert(1);
}";
var fnc = aMethod(s);
如果這是字符串,我想要一個名為 fnc 的 function。 和fnc();
彈出警報屏幕。
eval("alert(1);")
不能解決我的問題。
從字符串創建函數的更好方法是使用
Function<\/code> :
var fn = Function("alert('hello there')");
fn();
我為從字符串創建函數的 4 種不同方法添加了 jsperf 測試:
將 RegExp 與 Function 類一起使用
使用帶有“return”的函數類
使用官方 Function 構造函數
使用評估
2 個結果樣本:
你很接近。
//Create string representation of function
var s = "function test(){ alert(1); }";
//"Register" the function
eval(s);
//Call the function
test();
這是一個工作小提琴。
是的,使用Function
是一個很好的解決方案,但我們可以更進一步,准備通用解析器來解析字符串並將其轉換為真正的 JavaScript 函數......
if (typeof String.prototype.parseFunction != 'function') {
String.prototype.parseFunction = function () {
var funcReg = /function *\(([^()]*)\)[ \n\t]*{(.*)}/gmi;
var match = funcReg.exec(this.replace(/\n/g, ' '));
if(match) {
return new Function(match[1].split(','), match[2]);
}
return null;
};
}
使用示例:
var func = 'function (a, b) { return a + b; }'.parseFunction();
alert(func(3,4));
func = 'function (a, b) { alert("Hello from function initiated from string!"); }'.parseFunction();
func();
這是jsfiddle
JavaScript
中的動態函數名Function
var name = "foo";
// Implement it
var func = new Function("return function " + name + "(){ alert('hi there!'); };")();
// Test it
func();
// Next is TRUE
func.name === 'foo'
來源:http: //marcosc.com/2012/03/dynamic-function-names-in-javascript/
eval
var name = "foo";
// Implement it
eval("function " + name + "() { alert('Foo'); };");
// Test it
foo();
// Next is TRUE
foo.name === 'foo'
sjsClass
https://github.com/reduardo7/sjsClass
Class.extend('newClassName', {
__constructor: function() {
// ...
}
});
var x = new newClassName();
// Next is TRUE
newClassName.name === 'newClassName'
這種技術可能最終等同於 eval 方法,但我想添加它,因為它可能對某些人有用。
var newCode = document.createElement("script");
newCode.text = "function newFun( a, b ) { return a + b; }";
document.body.appendChild( newCode );
使用帶有 return 的
new Function()<\/code>並立即執行它。
帶有動態參數的示例:
let args = {a:1, b:2}
, fnString = 'return a + b;';
let fn = Function.apply(Function, Object.keys(args).concat(fnString));
let result = fn.apply(fn, Object.keys(args).map(key=>args[key]))
如果你有一個字符串形式的 function 表達式,你想把它變成 function,那么你需要在傳遞給new Function
的字符串中包含一個 return 語句。
const strFn = "const sum = (a, b) => a + b"
const newFn = new Function(`${strFn}; return sum`)();
console.log(newFn(2, 3)) // 5
如果不立即執行,可以使用function.call
方法執行。 請記住,它采用的第一個參數是this
值
const newFn = new Function('const arrMultiplier = (arr) => arr.map(num => num * 2); return arrMultiplier')
console.log(newFn.call({}).call({}, [6, 4, 1, 0])); // [12, 8, 2, 0]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.