The CreatorCon Call for Content is officially open! Get started here.

Instantiate script include from name of script in a variable

krr
Mega Guru

Is there a method to instantiate a script include if we have the name of the script include in a variable?

This example works as a background script, but not as part of a business rule

var scriptName = 'MyScriptInclude';
		
var obj = new this[scriptName];
obj.myMethod();

When running inside of a business rule this returns this error

com.glide.script.RhinoEcmaError: undefined is not a function.

At this line

var obj = new this[scriptName];
1 ACCEPTED SOLUTION

When we call script include its important to have its type function. In your case, the value is coming like a string so it doesn't take it and throw an error. Although, eval is never recommended but this is the only way to go as to call script include dynamically it should be of type function and that is what eval() do.

I recently explained the same in the latter part of the below thread.  

https://community.servicenow.com/community?id=community_question&sys_id=8010e9dedb22585466f1d9d96896...

 

Thanks & Regards,

Sharjeel

Regards,
Muhammad

View solution in original post

4 REPLIES 4

Allen Andreas
Administrator
Administrator

Hi,

To call it you also need () on it, so you can try:

var scriptName = 'MyScriptInclude()';
		
var obj = new this[scriptName];
obj.myMethod();

or

var scriptName = 'MyScriptInclude()';
		
var obj = new scriptName;
obj.myMethod();

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


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

Unfortunately neither of these work.

I've used a rather distasteful eval() statement for the time being to get this to work for now.

var scriptName = 'MyScriptInclude';
		
var obj = eval('new ' + scriptName);
obj.myMethod();

Yeah, seems you're pretty limited with options if doing this from the server side.

I think in this edge case scenario you should be fine.

Glad you got it working!


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

When we call script include its important to have its type function. In your case, the value is coming like a string so it doesn't take it and throw an error. Although, eval is never recommended but this is the only way to go as to call script include dynamically it should be of type function and that is what eval() do.

I recently explained the same in the latter part of the below thread.  

https://community.servicenow.com/community?id=community_question&sys_id=8010e9dedb22585466f1d9d96896...

 

Thanks & Regards,

Sharjeel

Regards,
Muhammad