我目前有一些大文件,我想将它们分解成较小的文件以方便编辑。我觉得这些“代码片段”不值得被创建为模块和/或如果这样做的话会与范围发生冲突。
因此,我宁愿将这些“剪辑”文件中的内容导入到当前执行范围中,然后评估它们。我想我会编写一个辅助函数来执行此操作(通过“主”js 文件在全局范围内设置。)但我遇到了障碍。
有没有办法从被调用函数中获取调用实例。
到目前为止我所拥有的:
global.acquire = (function() {
var cache = {};
var fileReader = require('fs');
return function (file, updateCache) {
var f = require.resolve(file);
if (f) {
if (cache.hasOwnProperty(f) && !updateCache) {
res = cache[f];
} else {
res = fileReader.readFileSync(f, {encoding: "utf8"});
}
cache[f] = res;
// Is there a way to get the calling function's instance so the eval will execute from the caller's scope?
return eval.apply(caller, '(' + res + ')');
} else {
throw "File not found";
}
}
}());
我知道我可以传递实例,或者 acquire.apply(),但如果我可以从函数内检索实例,那感觉有点草率。
最佳答案
如果不传递特定变量或使用 this
设置您想要/需要访问的数据,则无法从该作用域外部的单独函数内获取调用者的作用域。
关于javascript - 从函数内部获取调用者实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23371112/