Dynamic function call in script include
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎04-29-2012 05:34 AM
In script include, I want to call method dynamically. eg. in script include I have test1() and test2() are created, now I want to call either test1() / test2. Is there any possibility to call function dynamically in script include? Below is the script I am trying to execute
var funName = 'test1';
eval(funName )();
Is there any other way to achieve dynamic function call as above script does't work?
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎05-02-2012 09:33 AM
without eval.
I do this with dynamically choosing a class to instantiate, rather than a function but the code's the same. You currently have to write your own function/method to get the function or class, but it goes something like this:
var funName = 'test1';
var x = getClassByName(funName);
x();
function getClassByName(jsClassName) {
return JSUtil.getGlobal()[jsClassName];
}
function test1() {
gs.print('test1 called');
}
you don't need that intermediate assignment of the value to x, but you can do that if you want to call the function again later.
Or, if it's actually an object you're instantiating it looks like this:
var className = 'Class1';
var klass = getClassByName(className);
var k = new klass();
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎01-31-2018 07:19 AM
If you're inside a script, you can call its functions by name since they are properties of the script object. For example, this should work:
var MyScript = Class.create();
MyScript.prototype = {
initialize: function(),
f1: function() { gs.info("I'm f1"); },
f2: function() { gs.info("I'm f2"); },
execute: function(name) { this[name](); }
}
Then you should be able to do something like:
var s = new MyScript()
s('f1');