Understanding and using inheritance in Script include

A few days ago I saw a question on the ServiceNow community about how inheritance works in a script include so I thought to write a short article about that.

In Script include we can write a function or we can create a class. In JavaScript, class is an object, an object can access properties and functions from another object, this we call Inheritance

Inheritance is a great way to create a parent/child hierarchy of classes. A good use case for inheritance is when you wish to indicate that one object is mostly similar to another, but with some variations.

Parent class(Base class) is a class that supplies base behavior to a child class. The child class then extends this base behavior to form its behavior

Let’s take an example

Suppose you would like to create a script that handles the behavior of tasks and incidents. as you know, a lot of behavior is in common between task and incident, so When crafting a task script, you should be crafting it in a way that can be open to an extension so that incident’s script can come along and build upon the task behavior.

Let’s write some code to see how this works in reality.

I create a class named TaskParentClass. The class takes GlideRecord as a parameter and contains three methods. those methods can work on Task and Incident.

var TaskParentClass = Class.create();
TaskParentClass.prototype = {
    initialize: function() {
	
    },
	WelcomeToTask:function(gr){
		
		gs.addInfoMessage('Welcome to task Number ' + gr.number);
	},
	getCI:function(gr){
		
		gs.addInfoMessage('CI Name is ' + gr.cmdb_ci);
	},
    type: 'TaskParentClass'
};

Now, Let’s inherit TaskParentClass. We are going to inherit the class using Object.extendsObject method.

var IncidentChildClass = Class.create();
IncidentChildClass.prototype = Object.extendsObject(TaskParentClass, {
    initialize: function() {
	
    },
getCaller:function(gr){
	
	gs.addInfoMessage('Caller Name is' + gr.caller_id.name);
},
    type: 'IncidentChildClass'
});

after extending the class using Object.extendsObject method, we expect all parent methods to be available to the child as well as ‘getCaller’ method which is implemented in the child class.

so, let’s validate by calling two methods, one from the parent and one from the child

// Calling Method from Parent Class
	new IncidentChildClass().WelcomeToTask(current);
// Calling Method from the current class
	new IncidentChildClass().getCaller(current);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s