Dynamically instantiate Script Include

Erik Gunther2
Kilo Guru

I'm trying to dynamically instantiate a Script Include. Based on some other forum responses here is what I've done in the Scripts-Background interface:

Script Include:

find_real_file.png

Scripts:
//Traditional approach: WORKS!
var obj = new global.TestAPI();
var result = obj.test();
gs.print(result);

//Dynamically calling method: WORKS!
var result2 = obj['test']();
gs.print(result2);

//Dynamically instantiating script include. FAILS!!!
var obj2 = this['TestAPI'](); //Fails
//var obj2 = this['global.TestAPI'](); //Fails
var result3 = obj2['test']();
gs.print(result3);

Note, I've tried some other things like

var obj2 = this['TestAPI()']; but this fails too.

 

 

1 ACCEPTED SOLUTION

Michael Jones -
Giga Sage

Well, this seemed to work for me, in a background script: 

var str = 'TestAPI'
var tm = new global[str]()
tm.test()

my .test() function was just gs.info('test called') and it showed up when I ran the code above. 

I hope this helps!

If this was helpful, or correct, please be kind and mark the answer appropriately.

Michael Jones - Proud member of the GlideFast Consulting Team!

I hope this helps!
Michael D. Jones
Proud member of the GlideFast Consulting Team!

View solution in original post

7 REPLIES 7

Allen Andreas
Administrator
Administrator

Hi,

My solution covers both a dynamic script include name as well as a dynamic method:

You can populate an object with values (can use dynamic of course) such as:

var obj = {
'SI': exampleAPI,
'm': 'test123'
}

then use additional script such as:

var f = new obj['SI']();
var result = f[obj.m]();

gs.info(result);

Which will return:

find_real_file.png

From script include:

var exampleAPI = Class.create();
exampleAPI.prototype = {
    initialize: function() {},
    test123: function() {
        return 'successful';
    },
    type: 'exampleAPI'
};

Please mark reply as Helpful/Correct, if applicable. Thanks!


Please consider marking my reply as Helpful and/or Accept Solution, if applicable. Thanks!

In you response you listed exampleAPI as a non-string value. If I intend to pass the name of the Script Include as a function parameter or in a Flow Designer scripted activity, what data type would I use?

Hi,

You would need to set it to a function object (use typeof in current form to see what type it is).

If you don't mind, since you're sort of having two conversations about this where each of your replies has revealed something pretty important as to how this solution may be given...can you perhaps give us the entire context.

Is this a scoped app? Is this string from somewhere else being passed in as a function a parameter? Anything else?

Both of those answers could change the approach so we'd like to know the full details, if you don't mind.

Please mark reply as Helpful/Correct, if applicable. Thanks!


Please consider marking my reply as Helpful and/or Accept Solution, if applicable. Thanks!