javascript - How to write function-y accepting parameter-fct_x which accesses var-a which is required to be defined in function-y? -


function x() {     return + 1; // can accessing var-a. }  function y(fct_x) {     var = 2;     fct_x(); // exception: not defined }  y(x);   // exception: see above         // x function access var-a required defined in function-y 

question: how write function-y above calling fct_x() within function-y not throw exception?
note: fct_x function (user given) accesses var-a. var-a not defined in function-x, required defined in function-y.

with referring is possible achieve dynamic scoping in javascript without resorting eval?, have tried this, not work.

why ask above question: question comes "mongodb mapreduce", this: there 3 properties , 28 functions available map-reduction. 1 of 28 function emit(key,value). (see mongodb doc).

take example,

function mapfunction() { emit(this.fielda, this.fieldb) }; db.collection.mapreduce(mapfunction, reducefunction, {...});  // calling mapreduce-function 

the emit-function within mapfunction not defined in mapfunction. "provided"/"defined" somewhere within function db.collection.mapreduce. how function-db.collection.mapreduce written able proivde such emit-function user-given-mapfunction call?

[var a] equivalent [function-emit]
[function y] equivalent [function-mapreduce]
[function x] equivalent [function-mapfunction]

if understood question correctly, you're looking dynamic scoping. javascript lexically scoped, capture variable, closure must textually within scope. otherwise, not possible, not counting more or less silly tricks like, example:

function makeclosure(context) {      return function() {          return context("a") + 1;      };  }    function y(evalthis) {      var = 2;        if(evalthis)          return eval(evalthis);        return makeclosure(y);  }    closure = y();  document.write(closure()) // 3

see is possible achieve dynamic scoping in javascript without resorting eval? more discussion , examples.

as mongodb question specifically, it's not possible in pure javascript inject variable function's scope (again, without resorting eval). mongo's map-reduce written in c++, not in js, , can manipulate scope in arbitrary ways:

_scope->setfunction("emit", etc 

see source.

for completeness, here's example eval:

function map(ary, fun) {        // define locals      var local = 42;        // re-evaluate function within scope      eval("fun=" + fun);        // fun sees our locals      return ary.map(fun);  }    document.write(      map([1,2,3], function(x) { return x * local }) // [ 42, 84, 126 ]  )


Comments

Popular posts from this blog

java - Plugin org.apache.maven.plugins:maven-install-plugin:2.4 or one of its dependencies could not be resolved -

Round ImageView Android -

How can I utilize Yahoo Weather API in android -