← All articles
◈ Tech & ServiceNowServiceNowScripting

Understanding and Using Inheritance in Script Includes

Posted on 6 Mar 2022 · 2 min read

A question about how inheritance works in Script Includes came up in the ServiceNow community recently, so I thought it was worth a short but complete article.

The Basics

In a Script Include, you can write a function or create a class. In JavaScript, a class is an object, and an object can access properties and functions from another object — this is called inheritance.

Inheritance is a great way to create a parent/child hierarchy of classes. It's most useful when you want to express that one object is mostly similar to another, but with some additions or variations.

The parent class (base class) supplies base behaviour to child classes. Child classes then extend that behaviour to form their own.

A Practical Example

Suppose you want to create scripts to handle the behaviour of both Tasks and Incidents. Because Incidents extend Tasks, there's a lot of shared behaviour. The smart approach is to write the Task behaviour in a parent class that Incident can extend.

Parent Class

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'
};

Child Class (using Object.extendsObject)

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'
});

Calling Both Parent and Child Methods

After extending with Object.extendsObject, all parent methods are available to the child class:

// Calling a method from the parent class
new IncidentChildClass().WelcomeToTask(current);

// Calling a method defined in the child class
new IncidentChildClass().getCaller(current);

Both calls work correctly. The child class has access to its own getCaller method as well as the parent's WelcomeToTask and getCI methods.

When to Use Inheritance

Use it when you have a family of related scripts that share significant logic. The pattern avoids duplication, makes each class easier to understand in isolation, and lets you add new child classes without touching the parent.