What are the implications of creating a Script Include with static function definitions?

mikeellis
Kilo Contributor

Can anyone help shed some insight on what happens within ServiceNow if I create a Script Include that defines a static class w/ static functions?

Example:

var StaticClass = {

      initialize: function() {

      },

  StaticFunction: function () {

  gs.addInfoMessage("StaticFunction() Called");

  },

      type: 'StaticClass'

};

Firstly, this code does work.   I can simply call StaticClass.StaticFunction() without instantiating StaticClass.

What I want to know is, is there any reason why wouldn't I want to do this?   Is there another solution/approach I'm missing for defining static methods within the platform?

All input is welcome - Thanks in advance!!

2 REPLIES 2

corbettbrasing1
Mega Guru

See this article Object-Oriented JavaScript Tip: Creating static methods, instance methods | Anselm Bradford



1.   There is no performance impact until you CALL the script include, whether that be creating a new object of your script include where the object holds all functions in 1 object of your script include, OR you directly call the static function where that static function becomes an object itself (which is why they don't have scope access to non static functions).   If you want to check the size of the two objects to see what takes up more memory you can use Object.getOwnPropertyNames(obj) in a log statement where obj is the static function or the prototype object you are calling when you use "new" to instantiate the script include.  


2.   The only other thing to keep in mind is scope.   Static functions will not have access to non static functions or variables.


Andreas R
Mega Expert

The biggest implication from what I can tell is that as ServiceNow throws tasks at threads, your static methods will not be able to share data, so your methods will be executing on different instances. You cannot create reliable singletons in ServiceNow, for instance, since for every thread your "static" `instance` field will be reinitialized.