I want to create three functions out of one javascript string containing the js source code.
Lets say i have the following code as one string:
"
function func1()
{
console.log('This comes from func1')
}
function func2()
{
console.log('This comes from func2')
}
function func3()
{
console.log('This comes from func3')
}
"
Now i want to create these three function as javascript functions and attach them to an object, like:
object1.func1 = function func1(){...}
object1.func2 = function func2(){...}
I have a lot of objects and want to be able to attach a script file that contains these three functions func1, func2 and func3. The script file can contain other functions too, but these getting called by one of the three functions. So a script file for an object could look like as follows:
"
// Main functions of a script file
// A script file MUST contain these three functions
function func1()
{
console.log('This comes from func1')
userFunc1();
// do some user code
}
function func2()
{
console.log('This comes from func2')
userFunc2();
// do some user code
}
function func3()
{
console.log('This comes from func3')
userFunc3();
userFunc4();
// do some user code
}
// User functions
// these are optional
function userFunc1()
{
// do stuff
}
function userFunc2()
{
// do stuff
}
function userFunc3()
{
// do stuff
}
function userFunc4()
{
// do stuff
}
"
I have no problem creating a function when the string only contains one function, like as follows:
var jsCode = "(function func1(){console.log('This comes from func1')})";
var script=new Function (jsCode);
script();
My problem is how to parse two or more functions out of one string and create these functions accordingly?
I don't want to use any libraries, just pure javascript and I don't want to use eval as it seems to be horribly slow.
Can somebody help me with this problem?
eval.evalis dangerous and should never be used, as it could execute arbitrary and malicious JS code: stackoverflow.com/questions/18269797/…functionand the next index offunction(or end of string), then taking a substring between the two to split the function apart.