I am trying to write a JavaScript loader for a project of mine for NW.js ( node-webkit ). I already sort of know my way around peg.js and estools (esprima/escodegen), so parsing the JavaScript modules into the various function and variable declarations is really no problem, the problem I have is with instantiating the different text-expressions and declarations into a separate context/object.
eval()
does not seem to work for turning a declaration-string into a variable of my choice.
$.context.fn = eval("function anonymous(a,b,c){ return a+b+c; }");
//$.context.fn = undefined..
The only thing I can successfully convert from text to variable is functions:
$.context.fn = new Function('a','b','c','return a+b+c;');
//$.context.fn = function(a,b,c){ ... }
But there doesn't seem to be an analogous way of going about turning a string into a class for example:
$.context.cl = new Class(params,body) ???
//error
Question:
Is there maybe some sort of loader library I could use for this or are there maybe some tips to get the whole thing working with eval()
after all?
eval
should work fine with any expressions :
$.context.fn = eval("(function anonymous(a,b,c){ return a+b+c; })");
$.context.cl = eval("(class { constructor() { … } … })");
However, eval
always captures the local scope, which you'll probably not want. Either go for global eval , or use the trick with the function constructor to get the scope that you want. To instantiate a class, just create a function that returns said class (or any other language construct):
$.context.fn = (new Function("function named(a,b,c){ return a+b+c; }\nreturn named;"))();
$.context.cl = (new Function("class Example { constructor() { … } … }\nreturn Example;"))();
Your problem is that
function anonymous(a,b,c){ return a+b+c; }
is a functions declaration, not a function expression. Function declaration do not return anything: they define a new function with the name provided. In this case the name is anonymous
.
You want to use a function expression instead. See this MDN section for an explanation of the differences. You can make a function expression by wrapping the function in parentheses:
$.context.fn = eval("(function anonymous(a,b,c){ return a+b+c; })");
Class declarations and class expressions work the same way:
$.context.cls = eval("(class MyArray extends Array {})")
You can create functions with eval:
1)
eval("function anonymous(a,b,c){ return a+b+c; }");
console.log(anonymous(1,2,3));
2)
eval('var fn = function(a,b,c) { return a+b+c;};');
console.log(fn(1,2,3));
3)
eval("function anonymous(a,b,c){ return a+b+c; }");
var fn = anonymous;
console.log(fn(1,2,3));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.