Question

evaling a string that declares an array with functions works fine. However, evaling a string that declares an object with functions does not work. Can anyone tell me why?

This JSFiddle and the following code demonstrate the problem:

"use strict";

// functions in arrays are ok:
var x = "[ function() {}, [function() {}] ]";
var o = eval(x);
console.log(o[1]);

// functions in objects are not ok (for some reason):
var y = "{a: function() {}, b: [function() {}] }";
var o = eval(y);
console.log(o['a']);

Only the second eval causes trouble.

In Chrome, I get:

Uncaught SyntaxError: In strict mode code, functions can only be declared at top level or immediately within another function.

In IE 11, I get:

Expected identifier

Was it helpful?

Solution

The problem isn't where you think it is.

Change

var y = "{a: function() {}, b: [function() {}] }";

to

var y = "({a: function() {}, b: [function() {}] })";

Or change the call to eval to

var o = eval('('+y+')');

to avoid eval thinking you pass a block instead of an object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top