Javascript calling eval on an object literal (with functions)

匿名 (未验证) 提交于 2019-12-03 02:26:02

问题:

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;   } };


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!