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