function myFunction() {
return a + 1; // any variable accessing var-a here can be anything.
}
function anotherFunction(callback) {
var a = 2;
callback(); // no exception thrown, a is defined in the scope
}
anotherFunction(myFunction); // no exceptions raised
// myFunction is any function that accesses var-a, which must be defined in anotherFunction
Question: How can I write anotherFunction similar to the example above so that calling the callback within it will not result in an exception?
Note: The callback is any user-provided function that accesses var-a. Var-a is not defined in the callback, but must be defined in anotherFunction.
I have attempted different approaches like this, and also explored alternatives such as this, but none of them worked.
The inspiration for this question comes from the concept of "MongoDB mapReduce", where one of the functions, emit(key, value), is provided within the map-reduce operation. Refer to (MongoDB documentation).
Consider this scenario:
function mapperFunction() { emit(this.fieldA, this.fieldB) };
db.collection.mapReduce(mapperFunction, reducerFunction, {...}); // invoking mapReduce operation
In the example above, the emit function used within mapperFunction is not defined within the scope of mapperFunction itself. It is somehow provided or defined within the db.collection.mapReduce function. How can the db.collection.mapReduce function be implemented to provide such functionality for a user-defined mapperFunction?
[var a] is equivalent to [emit function]
[anotherFunction] corresponds to [mapReduce function]
[myFunction] corresponds to [mapperFunction]