var foo = (function(){
var x = "bar";
return function(){
console.log(x);
};
})();
console.log(foo.toString()); // function() {console.log(x);}
(foo)(); // 'bar'
eval('(' + foo.toString()+')()')); // error: x is undefined
是否有解析(修改)函数的技术,因此来自外部范围的引用成为本地引用,例如:
function() {console.log(x);}
变成:
function() {console.log("bar");}
该函数现在可以被字符串化并通过网络传输并在另一个运行时执行。
也许可以将函数解析为抽象语法树,然后对其进行修改?引用总是超出范围(不可用),对吧?
目标:
我正在将过滤器函数从节点运行时序列化到 postgresql plv8 运行时。现在过滤器函数有接口(interface):dbClient.filter((row, age) => row.age > age), ageFromOuterScope).then(matches => ...)
我想要接口(interface) dbClient.filter((row) => row.age > age)).then(matches => ...),其中 age 是来自外部范围的引用。
更新:
我只能想象一种解决方案。分析函数,检测对函数外部变量的引用,然后重写原函数:
function(row) {
return row.age > age
}
收件人:
function(row, age) {
return row.age > age
}
检测到的变量也应该添加到表示数组的字符串中,例如:
var arrayString = '[age]'
然后评估字符串:
var functionArgs = eval(arrayString)
最后:
dbClient.filter(modifiedFunction, ...functionArgs).then(matches => ...)
最佳答案
要在范围外公开私有(private)变量,您需要范围内的另一个函数重写 toString 返回的方法描述。然后使用该函数而不是 toString 来检索方法描述。
var foo = (function(){
var x = "bar";
var f = function(){
console.log(x);
};
f.decl = function() {
return f.toString().replace("(x)", "(\""+x+"\")");
}
return f;
})();
console.log(foo.decl()); // function() {console.log("bar");}
eval("("+foo.decl()+")()"); // bar
关于javascript - 解析 javascript 函数中的外部范围引用以进行序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33061578/