자바 스크립트를 사용하여 문자열에서 함수를 만드는 방법이 있습니까?
예를 들면 다음과 같습니다.
var s = "function test(){
alert(1);
}";
var fnc = aMethod(s);
이것이 문자열이면 fnc라는 함수를 원합니다. 그리고 fnc();
경고 화면이 나타납니다.
eval("alert(1);")
내 문제를 해결하지 못합니다.
문자열에서 함수를 만드는 4 가지 방법에 대한 jsperf 테스트를 추가했습니다.
Function 클래스와 함께 RegExp 사용
var func = "function (a, b) { return a + b; }".parseFunction();
"return"과 함께 Function 클래스 사용
var func = new Function("return " + "function (a, b) { return a + b; }")();
공식 함수 생성자 사용
var func = new Function("a", "b", "return a + b;");
Eval 사용
eval("var func = function (a, b) { return a + b; };");
문자열에서 함수를 만드는 더 좋은 방법은 다음을 사용하는 것입니다 Function
.
var fn = Function("alert('hello there')");
fn();
이것은 현재 범위의 변수 (전역 적이 지 않은 경우)가 새로 생성 된 함수에 적용되지 않는다는 장점 / 단점을 가지고 있습니다.
인수 전달도 가능합니다.
var addition = Function("a", "b", "return a + b;");
alert(addition(5, 3)); // shows '8'
당신은 꽤 가깝습니다.
//Create string representation of function
var s = "function test(){ alert(1); }";
//"Register" the function
eval(s);
//Call the function
test();
여기 에 작동하는 바이올린이 있습니다.
Yes, using Function
is a great solution but we can go a bit further and prepare universal parser that parse string and convert it to real JavaScript function...
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;
};
}
examples of usage:
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();
here is jsfiddle
Dynamic function names in JavaScript
Using 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'
Source: http://marcosc.com/2012/03/dynamic-function-names-in-javascript/
Using eval
var name = "foo";
// Implement it
eval("function " + name + "() { alert('Foo'); };");
// Test it
foo();
// Next is TRUE
foo.name === 'foo'
Using sjsClass
https://github.com/reduardo7/sjsClass
Example
Class.extend('newClassName', {
__constructor: function() {
// ...
}
});
var x = new newClassName();
// Next is TRUE
newClassName.name === 'newClassName'
This technique may be ultimately equivalent to the eval method, but I wanted to add it, as it might be useful for some.
var newCode = document.createElement("script");
newCode.text = "function newFun( a, b ) { return a + b; }";
document.body.appendChild( newCode );
This is functionally like adding this <script> element to the end of your document, e.g.:
...
<script type="text/javascript">
function newFun( a, b ) { return a + b; }
</script>
</body>
</html>
Use the new Function()
with a return inside and execute it immediately.
var s = `function test(){
alert(1);
}`;
var new_fn = new Function("return " + s)()
console.log(new_fn)
new_fn()
An example with dynamic arguments:
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]))
'code' 카테고리의 다른 글
priorityQueue를 최대 priorityqueue로 변경 (0) | 2020.08.31 |
---|---|
CGPoint 데이터가있는 NSLog (0) | 2020.08.31 |
대소 문자를 무시하는 문자열의 startsWith () 메소드 (0) | 2020.08.30 |
Android MultiDex 란 무엇입니까? (0) | 2020.08.30 |
Subversion을 사용하여 두 개의 분기 수정본 병합 (0) | 2020.08.30 |