I am needing to find the argument passed to a function from the function.
Let us suppose I have a function called foo:
function foo() {
var a = 3;
var b = "hello";
var c = [0,4];
bar(a - b / c);
bar(c * a + b);
}
function bar(arg) { alert(arg) }
As it is now, of course, bar will always alert NaN.
Inside of the function bar, I want to obtain the argument in the form it was originally passed. Furthermore, I want to be able to access the values of a, b, and c from the bar function. In other words, I would like something of this nature:
bar(a - b / c);
function bar() {
//some magic code here
alert(originalArg); //will alert "a - b / c"
alert(vars.a + " " + vars.b + " " + vars.c); //will alert "3 hello 0,4"
}
You may not think this is possible, but I know you can do weird things with Javascript. For example, you can display the code of the calling function like this:
function bar() {
alert(bar.caller);
}
I am willing to bet a few dollars that with some sort of finagling you can get a the original form of the argument and the values of the variables in the argument.
I can easily see how you could do it if you were allowed to call bar in a form like this:
bar(function(){return a - b / c}, {a: a, b: b, c: c});
But that is too convoluted and therefore unacceptable. The way bar is called may not be changed.
Your question is misguided and sick and…I love it! Here is a short solution which I will explain.
The key is the
meld(f, g)function which returns a new anonymous function that acts just likefwhile calling and exposing its internals to a copy ofg. You see, the originalgis in a bad position to see anything aboutf— at best it can useg.callerand tons of regular expressions.Here is the pseudo code for
meld. First makefan anonymous function, suitable for evaluating and assigning to a variable later on; for instancefunction foo() {becomesfunction() {. Next findg‘s real name and quote any arguments passed to it from newf. Next, insert a copy ofginside newf. It will mask the global name and it will have access tof‘s local variables as if they were its own. Finally, evaluate this anonymous function and return it.So how do we use
meld? Just replacefoowithmeld(foo, bar)and then usefooas you normally would.OK, now for the limitations. I didn’t want to spend lots of effort refining the regex inside
meldto quoteg‘s argument(s) against all possibilities. This would just have been a distraction from the concept of the solution as a whole. You’ll need to change it to properly handle more than one argument and escape any which themselves have quotes or parentheses.