Javascript variable scope when dynamically referencing functions -
Javascript variable scope when dynamically referencing functions -
i'm trying create function creates "proxy" around object's method. "proxy" used handle web requests , phone call target method. proxy function looks similar this:
var proxy = function(c) { var proxy = {}; for(var fellow member in c) { var args = c[member].tostring().match (/function\s*\w*\s*\((.*?)\)/)[1].split (/\s*,\s*/); proxy[member] = function(params) { var methodargs = args.map(function(argname) { homecoming params[argname]; }); homecoming c[member].apply(c, methodargs); } } homecoming proxy; };
so if have original controller,
var c = { sum: function(x, y) { homecoming x + y; }, multiply: function(x, y) { homecoming x * y; } };
calling proxy(c) on homecoming proxy object sum() , multiply() functions. however, because of scope of member
variable in proxy() function, phone call lastly referenced function in c - in case, multiply().
var cproxy = proxy(c); //this should phone call c.sum, instead calls c.multiply cproxy.sum({ x: 3, y: 8 });
how reference right function in proxy() function right method gets called?
the next worked me, create closure member
var proxy = function(c) { var proxy = {}; for(var fellow member in c) { !function(member){ var args = c[member].tostring().match (/function\s*\w*\s*\((.*?)\)/)[1].split (/\s*,\s*/); proxy[member] = function(params) { var methodargs = args.map(function(argname) { homecoming params[argname]; }); homecoming c[member].apply(c, methodargs); } }(member) } homecoming proxy; }; console.log( cproxy.sum({x: 3,y: 8})) // returns 11 console.log( cproxy.multiply({x: 3,y: 8})) //returns 24
javascript
Comments
Post a Comment