calling a dynamic function in javascript
is it possible to call a dynamic method in javascript. ie suppose i have in my page 2 methods as such:
function id1_add()
{
return 1;
}
function id2_add()
{
return 2;
}
i also have this functio开发者_如何学JAVAn:
function add()
{
var s1='id1';
s1+'_add()'; //???
}
is it possible to call for example id1_add() in such:
s1+'_add()';
so the method call depends on a previous string?
In the specific case of function declared in the global scope only, you can do
window[s1 + "_add"]();
Note this will not work for nested functions. This also relies on the global object being mapped to window
, which is the case in all scriptable browsers.
Aside from Tim's method you can also eval(s1+'_add()');
.
However this method can be unsafe if not used correctly.
See When is JavaScript's eval() not evil?
A better option would be to have a function to which you pass a different parameter depending on what you want to do.
精彩评论