Registered User
Registered User

Reputation: 3699

Executing dynamically passed function call with jQuery

I have this function call passed as a string:

var dcall = "tumbsNav(1)";

Is it possible to execute this dynamically like exec in SQL??

exec(dcall)

Upvotes: 0

Views: 305

Answers (4)

Porco
Porco

Reputation: 4203

Use eval(dcall).

As others have mentioned eval is considered bad practice. The main reasons for this are

1) Improper use can leave your code vulnerable to injection attacks.

2) Maintaining code becomes more difficult (no line numbers, can't use debugging tools)

3) Executes more slowly (browsers can't compile)

4) Scope becomes impossible to predict.

However, if you understand all these then eval can be very helpful.

Upvotes: 1

Ruan Mendes
Ruan Mendes

Reputation: 92274

Wherever you're storing

var dcall = "tumbsNav(1)";

You can instead store

var dcall = function() {
   return tumbsNav(1);
};

Wherever you were calling it, instead of calling

eval(dcall);

You can instead call

dcall();

The only case this wouldn't work is if tumbsNav wasn't defined at the time var func = ... is called. Then you would have to store the string. If the string is completely under your control, then there's no security hole, but be aware of all the problems mentioned by @Porco

As Kolink mentioned, my example would not cause a problem if tumbsNav was not defined when assigning it with a wrapped anonymous function that calls tumbs. The comment above would only make sense if the example had been the following:

var dcall = tumbsNav, darg = 1;
// later in the code, you can call
dcall(darg) ;

Upvotes: 1

apsillers
apsillers

Reputation: 115950

To do this, you want eval(dcall).

eval can open terribly security holes and performance issues in your program. If you need to use it, that usually means you have designed your program poorly.

Instead, you might keep a reference to the function you want to call and hold an array of arguments and use apply, e.g., tumbsNav.apply(null, [1]);. I don't know your code, so that's most general solution I can offer.

Upvotes: 3

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

eval is the equivalent, but you should NOT use it.

Instead, pass the function like this:

var dcall = function() {tumbsNav(1);};

Then call it with:

dcall();

Upvotes: 3

Related Questions