Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
678 views
in Technique[技术] by (71.8m points)

import - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...