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

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

问题描述

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



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



以下是评估代码:

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

以下是我在外部文件中使用的一些示例代码:

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

我的目标是放大对象字面量(包含所有的库代码)到一个局部变量上,这样我就可以引用它的属性/函数,就像它们包含在它们自己的命名空间中一样。

解决方案


$ b

 <$替换 var lib = eval(code);  c $ c> var lib = eval('('+ code +')'); 

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

当函数名称丢失时,块内的代码将被读取为标记的匿名函数语句,这是无效的。



添加了parens之后,大括号被用作对象文字(按照预期),并且 eval 的返回值是一个对象,使用 fetchData 方法。然后,你的代码将会工作。


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.

解决方案

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.

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

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