I want to load more than one function dynamically:
var str = "function foo() {} function bar() {}";
var functions = eval(???);
functions.foo();
Can this be done with eval? I was only successful with a single function.
With eval. Not recommended.
var str = "function foo() { console.log('foo'); } function bar() { console.log('bar'); }";
eval(str);
foo();
You could use an object and put the functions inside. You can later add a function with assignment.
var functions = {
foo: function () { console.log('foo'); },
bar: function () { console.log('bar'); }
};
functions.foo();
functions.baz = function () { console.log('baz'); }
functions.baz();
eval will execute certain string but it will not return anything. So functions will be undefined
eval will also run the given string in current scope. So the parsed functions will not necessarily be created in global scope.
Sample:
var str = "function foo1() {console.log('foo1')} function bar1() {console.log('bar1')}";
var functions = eval(str);
console.log(functions);
foo1();
(function() {
var str = "function foo2() {console.log('foo2')} function bar2() {console.log('bar2')}";
var functions = eval(str);
foo2();
})()
try {
foo2();
} catch (ex) {
console.log(ex.message)
}
My suggestion, create a new JS file and load it dynamically.
With functions.foo(); you try to access the property foo of the object functions and this will give you an undefined.
You could replace you string of functions simply with an object like
var functions = {
foo: function() {},
bar: function() {}
}
This avoids also the usege of eval().
Now you can access each property with functions.<functionName>;. You can add propertys dynamicly at runtime in JavaScript. So there is no usecase for eval in your problem
var functions = {
foo: function() { console.log('foo') },
bar: function() { console.log('bar') }
}
function addNewFunction(object, functionName, functionImplementation) {
object[functionName] = functionImplementation
}
addNewFunction(functions, 'ok', function() { console.log('ok') })
functions.foo()
functions.ok()
evalfor this task is most likely wrong.