Newer Version Available

This content describes an older version of this product. View Latest

eval() Function is Limited by Locker Service

In Locker Service, use of the eval() function is supported to enable use of third-party libraries that evaluate code dynamically. However, it is limited to work only in the global scope of the namespace. The eval() function can’t access the local variables within the scope in which it’s called.

Normally, eval() has two modes of execution. When you invoke eval() directly, it works in the local scope. When you invoke it via a reference, it works in the global scope. Locker Service only supports the latter.

For example, suppose that you execute the following code:

1window.foo = 1;
2function bar() {
3  var foo = 2;
4  return eval("foo");
5}

A call to bar() returns 2 when evaluation is performed in the local scope, and returns 1 when it’s performed in the global scope. If you must use variables from the local scope, refactor your code. Use a Function(), declare the local variables as parameters, pass them as arguments, and add a return statement:

1window.foo = 1;
2function bar() {
3  var foo = 2;
4  return Function("foo","return foo")(foo);
5}