javascript - Return variable function without parameters -


i'm trying write javascript function gets variables , returns function contains values without taking them parameters or referencing them.

a simple example:

function foo(a,b) {     return function(x) {         //doing values of , b, example:         return a*x + b;     } } 

so if do:

var c = foo(2,3); var d = foo(4,5); 

c , d like:

c:  function(x) {     return 2*x + 3; } d: function(x) {     return 4*x + 5; } 

i want foo() replace variables a,b values before returning new function. c , d dont need refer vars outside themselves.

i work casperjs , try dynamically create functions executed casper.evaluate() sandboxes executed functions. why wouldn't work way described in example.

any ideas how solve this? alot!

edit:

why need this? try write abstract crawler casperjs. there "main"-function accesses object-variable (var site = {...}) containing multiple functions casper.evaluate() takes arguments, 1 one. these functions executed sandboxed on opened webpage cannot access variables outside webpage. can different things 1 kind of tag contains link/image/reference, replaces reference , returns of them in list. function used links, images, css-files, js-files etc. , needed different selector, attribute-name (and maybe 1-2 other variables) each of them. cannot give them arguments function, because every function might need different number of arguments , casper.evaluate(site[i]['method']) call not know them. calls function without arguments. that's why thought implementing function generates these functions nicest way. apparently doesn't work way planned.

of course copy function , replace few variables. create lot of redundant code , bring of disadvantages.

another idea: functions called specific number of arguments stored inside same object: casper.evaluate(site[i]['method'],site[i]['arg0'],site[i]['arg1']...)

i think should work not nice because every function must have specific number of arguments if doesn't need one. , works long no function needs more arguments.

maybe work you. example allowing perform function number of arguments.

function foo() {     var func = function() {         //doing arguments of original function:         return arguments;     };     var allargs = array.prototype.slice.call(arguments); // 1     allargs.unshift(null); // 2     return function.prototype.bind.apply(func, allargs); // 3 } 
  1. get arguments of outher function , covert them array
  2. put null @ beginning of arguments list
  3. return copy of inner function has bound arguments outher function. null put beginning of allargs array used this argument bind function.

example usage:

var c = foo(1,2,3,4,5,6); c(7); // returns: [1, 2, 3, 4, 5, 6, 7] 

Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -