Javascript calling eval on an object literal (with

2019-01-26 18:39发布

问题:

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.

回答1:

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.



回答2:

You cannot evaluate

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

Because it is not a valid expression (Object literals on their own are interpreted as blocks. fetch: function () { } is not a valid expression).

Try

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