Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript calling eval on an object literal (with functions)

Disclaimer: I fully understand the risks/downsides of using eval but this is one niche case where I couldn't find any other way.

In Google Apps Scripting, there still is no built-in capability to import a script as a library so many sheets can use the same code; but, there is a facility built-in where I can import text from a plaintext file.

Here's the eval-ing code:

var id = [The-docID-goes-here];
var code = DocsList.getFileById(id).getContentAsString();
var lib = eval(code);
Logger.log(lib.fetchDate());

Here's some example code I'm using in the external file:

{
  fetchDate: function() {
    var d = new Date();
    var dateString = (d.getMonth() + 1) + "/" + d.getDate() + "/" + d.getFullYear();
    return dateString;
  }
}

What I'm aiming for is to drop a big object literal (containing all the library code) onto a local variable so I can reference it's properties/functions like they're contained in their own namespace.

like image 447
Evan Plaice Avatar asked Jan 20 '12 23:01

Evan Plaice


People also ask

Which is faster eval () or new function ())?

`Function() is a faster and more secure alternative to eval().

Why eval is not recommended?

Malicious code : invoking eval can crash a computer. For example: if you use eval server-side and a mischievous user decides to use an infinite loop as their username. Terribly slow : the JavaScript language is designed to use the full gamut of JavaScript types (numbers, functions, objects, etc)… Not just strings!

Is eval built in function in JavaScript?

The eval() function in JavaScript is used to evaluate the expression. It is JavaScirpt's global function, which evaluates the specified string as JavaScript code and executes it. The parameter of the eval() function is a string. If the parameter represents the statements, eval() evaluates the statements.


1 Answers

Replace var lib = eval(code); with:

var lib = eval('(' + code + ')');

When the parens are omitted, the curly braces are being interpreted as markers of a block of code. As a result, the return value of eval is the fetchData function, instead of a object containing the function.

When the function name is missing, the code inside the block is read as a labelled anonymous function statement, which is not valid.

After adding the parens, the curly braces are used as object literals (as intended), and the return value of eval is an object, with the fetchData method. Then, your code will work.

like image 138
Rob W Avatar answered Oct 04 '22 02:10

Rob W