用fs.readFileSync和eval内容读取文件…哪个范围有function? 如何访问?

我最近试图将文件导入到我现有的node.js项目中。 我知道这应该写一个模块,但我包括我的外部JavaScript文件是这样的:

eval(fs.readFileSync('public/templates/simple.js')+'') 

simple.js的内容如下所示:

 if (typeof examples == 'undefined') { var examples = {}; } if (typeof examples.simple == 'undefined') { examples.simple = {}; } examples.simple.helloWorld = function(opt_data, opt_sb) { var output = opt_sb || new soy.StringBuilder(); output.append('Hello world!'); return opt_sb ? '' : output.toString(); }; 

(是的,谷歌封闭模板)。

我现在可以使用以下方式调用模板文件:

 examples.simple.helloWorld(); 

一切都像预期一样工作。 然而,我无法弄清楚这些函数的范围是什么,我可以访问这个例子对象。

一切都运行在一个node.js 0.8服务器,就像我说的工作…我只是不知道为什么?

谢谢澄清。

eval()把variables放到你调用的地方的局部范围内。

就好像eval()被string参数中的代码所取代。

我build议将文件的内容更改为:

 (function() { ... return examples; })(); 

这样,你可以说:

 var result = eval(file); 

这将是显而易见的地方。

注意: eval()是一个巨大的安全风险; 请确保您只能从可信来源阅读。