Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a JavaScript function that has its name as a string

Tags:

javascript

How can I call the following?

var ccall="search.clearMultiSelect";

I have tried the following:

  1. window[ccall]();
  2. ccall();

Both didn't work (and I get why). I was able to achieve it by eval but is there any other way without using eval?

I cannot split the string or manipulate the string, except for adding something at the beginning or end.

Basically the server, in it's response, contains the name of the function to execute on success of an operation, which in this case is as above.

like image 687
aWebDeveloper Avatar asked Apr 25 '26 01:04

aWebDeveloper


1 Answers

window[ccall]() wouldn't work because window doesn't contain a function by the name "search.clearMultiSelect". If you can use split, try something like:

window[ccall.split('.')[0]][ccall.split('.')[1]]();

For a function of depth greater than 2, you can loop through the split('.') array:

var f = window;
var ccallArray = ccall.split('.');
for (var i = 0; i < ccallArray.length; i++){
    f = f[ccallArray[i]];
}
f();

DEMO

like image 130
tewathia Avatar answered Apr 28 '26 04:04

tewathia