Javascript 在对象文字上调用 eval(带函数) [英] Javascript calling eval on an object literal (with functions)

查看:52
本文介绍了Javascript 在对象文字上调用 eval(带函数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

免责声明:我完全理解使用 eval 的风险/缺点,但这是一个我找不到任何其他方法的小众案例.

Disclaimer: I fully understand the risks/downsides of using eval but this is one niche case where I couldn't find any other way.

在 Google Apps Scripting 中,仍然没有将脚本作为库导入的内置功能,因此许多工作表可以使用相同的代码;但是,有内置工具,我可以在其中从纯文本文件导入文本.

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.

这是评估代码:

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.

推荐答案

var lib = eval(code); 替换为:

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

当省略括号时,花括号被解释为代码块的标记.因此,eval 的返回值是 fetchData 函数,而不是包含该函数的对象.

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.

添加括号后,大括号用作对象字面量(如预期),eval 的返回值是一个对象,带有 fetchData 方法.然后,您的代码将起作用.

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.

这篇关于Javascript 在对象文字上调用 eval(带函数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆