By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
437,712 Members | 2,174 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 437,712 IT Pros & Developers. It's quick & easy.

How to call javascript function dynamically

100+
P: 184
Hi All,

How do i call the javascript function dynamically from another javascript function?
Example:
<script>
function getStructure(attrName)
{
//attrName is dynamic one...
for example if attrName is 'getName' & 'getValue'
I have to call corresponding Javascript function as getName() and getValue()

}
</script>

Thanks in Advance.
Jul 9 '08 #1
Share this Question
Share on Google+
5 Replies


hsriat
Expert 100+
P: 1,654
You could use eval. (although its not recommended)
Expand|Select|Wrap|Line Numbers
  1. function getStructure(attrName)
  2. {
  3.    //attrName is dynamic one...
  4.    //for example if attrName is 'getName' & 'getValue'
  5.    //I have to call corresponding Javascript function as getName() and getValue()
  6.    if (typeof(attrName) == 'function')
  7.    eval(attrName + '()');
  8. }
Jul 9 '08 #2

rnd me
Expert 100+
P: 427
use functionName.call or functionName.apply instead of evaling it.

apply will let you pas the arguments in an array as the second argument:

Expand|Select|Wrap|Line Numbers
  1. function sum( a, b){
  2.    return a+b;
  3. }
  4.  
  5.  
  6. alert(sum.apply(this, [3,6])) // shows 9
there is one aspect to hsriats code thatr may be useful to you: it will close the scope around the remote function so that that function's code can see local variables. this can also cause headaches, such as when a default value appears in a common var name, like i.
Jul 9 '08 #3

hsriat
Expert 100+
P: 1,654
But functionName.call or functionName.apply would again expect the actual function name. How to use a variable for that functionName?
Jul 9 '08 #4

acoder
Expert Mod 15k+
P: 16,027
How about:
Expand|Select|Wrap|Line Numbers
  1. var val = "sum";
  2. alert(window[val].apply(this, [3,6]));
Jul 10 '08 #5

rnd me
Expert 100+
P: 427
But functionName.call or functionName.apply would again expect the actual function name. How to use a variable for that functionName?
Expand|Select|Wrap|Line Numbers
  1. function getStructure(attrName){
  2.    funOb = this[attrName] || window[attrName] || new Function("return new Error();");
  3.   funOb.apply( this, [this] );
  4. }
Jul 11 '08 #6

Post your reply

Sign in to post your reply or Sign up for a free account.