【发布时间】:2014-12-16 13:05:32
【问题描述】:
function x() {
return a + 1; // it can be anything accessing var-a.
}
function y(fct_x) {
var a = 2;
fct_x(); // exception: a is not defined
}
y(x); // exception: see above
// x is any function which will access var-a which is required to be defined in function-y
问题:如何写一个像上面这样的function-y,这样在function-y中调用fct_x()就不会抛出异常?
注意:fct_x 是访问 var-a 的任何函数(用户给定)。 var-a 没有在function-x 中定义,但需要在function-y 中定义。
提到Is it possible to achieve dynamic scoping in JavaScript without resorting to eval?,我也试过this,但还是不行。
我为什么要问上面的问题: 这个问题来自“MongoDB mapReduce”,像这样: 地图缩减有 3 个属性和 28 个函数可用。 28 个函数之一是 emit(key,value)。 (See MongoDB doc).
举个例子,
function mapFunction() { emit(this.fieldA, this.fieldB) };
db.collection.mapReduce(mapFunction, reduceFunction, {...}); // calling mapReduce-function
mapFunction 中的 emit-function 未在 mapFunction 中定义。它在函数 db.collection.mapReduce 中的某处“提供”/“定义”。如何编写 function-db.collection.mapReduce 以便能够为 user-given-mapFunction 调用提供这样的发射函数?
[var a] 等价于 [function-emit]
[function y] 等价于 [function-mapReduce]
[function x] 等价于 [function-mapFunction]
【问题讨论】:
标签: javascript mongodb