I'm trying to write a JavaScript function that gets some variables and returns a function that contains their values without taking them as parameters or referencing them.
A simple example:
function foo(a,b) {
return function(x) {
//doing something with values of a and b, for example:
return a*x + b;
}
}
So if I do:
var c = foo(2,3);
var d = foo(4,5);
c and d will look like:
c: function(x) {
return 2*x + 3;
}
d: function(x) {
return 4*x + 5;
}
I want foo() to replace the variables a,b with their values before returning the new function. So c and d dont need to refer to some vars outside themselves.
I work with CasperJS and try to dynamically create functions to be executed by casper.evaluate() which sandboxes the executed functions. This is why it wouldn't work the way described in the example.
Any ideas how to solve this? Thanks alot!
EDIT:
Why do I need this? I try to write an abstract crawler with CasperJS. So there is a "main"-function that accesses an object-variable (var site = {...}) containing multiple functions which casper.evaluate() takes as arguments, one by one. These functions are executed sandboxed on the opened webpage so they cannot access any variables outside the webpage. They can do very different things but mostly they look for one kind of tag that contains a link/image/reference, replaces this reference and returns all of them in a list. This function could be used for links, images, css-files, js-files etc. and only needed a different selector, attribute-name (and maybe 1-2 other variables) for each of them. I cannot give them as arguments to this function, because every function might need a different number of arguments then and the casper.evaluate(site[i]['method']) call does not know about them. It calls the function without any arguments. That's why I thought implementing a function that generates these functions would be the nicest way. But apparently this doesn't work the way I planned.
Of course I could just copy this function and replace the few variables. But this would create a lot of redundant code and bring all of its disadvantages.
Another idea: the functions are called with a specific number of arguments which are stored inside the same object: casper.evaluate(site[i]['method'],site[i]['arg0'],site[i]['arg1']...)
I think this should work but is not very nice because every function must have this specific number of arguments even if it doesn't need one. And it only works as long as no function needs more arguments.