1

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.

Ickbinet
  • 277
  • 3
  • 12
  • 2
    What is the use case where you want to use that? Using `eval` for this task is most likely wrong. – t.niese Aug 30 '17 at 11:37

4 Answers4

1

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();
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

With functions.foo(); you try to access the property foo of the object functions and this will give you an undefined.

Solution

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

Example

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()
Community
  • 1
  • 1
Roman
  • 4,922
  • 3
  • 22
  • 31
0

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.

Reference Links:

Community
  • 1
  • 1
Rajesh
  • 24,354
  • 5
  • 48
  • 79
0

var foo = '( function foo() {} )'

var bar = '( function bar() {} )'

declare function with variable, then use the eval

var result = eval(foo)

result variable get the result of the foo() function