Possible Duplicate:
Why is using the JavaScript eval function a bad idea?
So I have read through MANY different methods on calling a function from a string, using window[](); and also eval();. I am wondering if for my situation (That is below) what method is exactly the right way to go ahead with, and if so, explain why. Also explain why eval(); isn’t exactly a good option, a lot of people say security, but why would security be an issue if you can get any browser plugin that enables you to change the script on that page? (example: firebug for firefox)
My current code:
funcOne(target).funcTwo(x, y, z);
How would call this using the recommended window[](); way? And why can’t I use this?:
eval('funcOne(target).funcTwo(x, y, z)');
I don’t want your annoyance of this question being asked many times, because I cannot currently think of a way to call a, as a call it, double function.
Thanks in advance!
In Javascript the syntax
a.bcan be replaced witha["b"]. So in your case you can usewhere of course it makes sense only if you are using variables instead of
"funcOne"and"funcTwo".If everything is instead fixed but you simply want to delay execution you can use “thunking” with an anonymous closure with
and then you can evaluate with
x()to get the desired result later.The last example will work correctly even if the variables
targetandx,yandzare local to the enclosing scope because the thunking closure will “capture” them.You should however pay attention to the fact that in Javascript the only way to create a new scope is to use a function (a block surrounded with
{and}is NOT a scope like happens in C++ and other languages).If you need to create several closures in a loop this can bite back and is a source of a quite common mistake…
here I used a closure for the
onclickevent on the div, but this is not going to work because all those functions will use the very sameivariable. Because in Javascript the only way to create a scope is using a function the solution is:This way the variable
iinside theonclickhandler will be different for each closure.This pattern of creating a function just to call it immediately is often used in Javascript when you need to create many independent closures so it’s better to know and understand it.