Javascript calling eval on an object literal (with functions)

Disclaimer: I fully understand the risks / disadvantages of using eval, but this is one of those nobody's where I could not find another way.

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

Here is the code:

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

Here is an example of the code that I use in an 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 cast a large object literal (containing all the library code) to a local variable so that I can reference its properties / functions, like those contained in their own namespace.

+4
source share
2 answers

Replace var lib = eval(code); on the:

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

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

When the function name is missing, the code inside the block is read as the designated anonymous function operator, which is not valid.

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

+11
source

You can not rate

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

Since this is not a valid expression (Object literals themselves 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; } }; 
+2
source

Source: https://habr.com/ru/post/1392159/


All Articles