Javascript calling eval on an object literal (with functions)

前端 未结 2 1895
没有蜡笔的小新
没有蜡笔的小新 2020-12-11 04:51

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

相关标签:
2条回答
  • 2020-12-11 04:57

    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;
      }
    };
    
    0 讨论(0)
  • 2020-12-11 05:01

    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.

    0 讨论(0)
提交回复
热议问题