开发者

calling a dynamic function in javascript

开发者 https://www.devze.com 2022-12-30 22:41 出处:网络
is it possible to call a dynamic method in javascript. ie suppose i have in my page 2 methods as such:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消