Hey, my fellow ServiceNow Developers!
Today, we will dive into one of JavaScript’s most important yet often misunderstood concepts: the “this” keyword.
In JavaScript, the “this” keyword can be very confusing and frustrating for even seasoned developers. But have no fear! We will walk through the “this” keyword together. Let’s get into it!
Basics of the “this” keyword
In JavaScript, the “this” keyword, sometimes called “execution context” or “context,” is a special reference to an object. It allows you to access the properties and methods of the object without having to reference the object’s name explicitly.
“What object?” you might ask. Unfortunately, it depends on where “this” is being used.
Most of the time, “this” works like the following:
Using “
this” in an object’s method? “this” will refer to the object.Using “
this” in a function that doesn’t belong to an object? In strict mode, “this” will be undefined. In non-strict mode, “this” will refer to the global thing. (an IIFE, or immediately-invoked function expression, falls into this category)Using “
this” outside any functions? “this” will refer to the global object.
Unexpected behavior of “this“
Because the “this” keyword changes based on how a function is called, you can sometimes run into trouble when using the methods of an object.
If there were an object whose method uses “this” to reference properties or methods on itself, and you were to save an object’s method to a variable and execute the function using that variable, you would experience the unexpected result of it simply not working.
That’s because when you store the object’s method into a variable, the resulting variable is a function not tied to a specific object. When executing that function, the “this” keyword is the global object.
Let’s look at a simplified example.
Here, we have a utils object with two methods.
forEach: This method will loop over an array and execute a callback for each element. This replicates one of the JavaScript methods you NEED to know about.callback: The function to call for every element in the array. This method will receive the element of the array at each iteration.
var utils = {
// For every item in an array, execute a callback
// and pass in the value of the element in the array
forEach: function (array, callback) {
var length = array.length;
for (var i = 0; i < length; i++) {
callback(array[i]);
}
},
// Add all the numbers of an array
addAllNumbers: function (numbers) {
var total = 0;
this.forEach(numbers, function (number) {
total = total + number;
});
return total;
}
};
If we call utils.addAllNumbers() and pass in an array of numbers, we will see that the addAllNumbers() method calls this.forEach() to iterate through all the numbers in the array and add them together.
utils.addAllNumbers([1,2,3,4,5])

But what happens if we save addAllNumbers() to a variable and try to call it, passing in an array of numbers?

The issue here is that our addAllNumbers() is now a function independent of utils. When the function is called, the “this” keyword is actually the global object, which in a browser is the window object.
The “this” keyword in ServiceNow Script Includes
In ServiceNow development, the place you will most commonly see the “this” keyword is in Script Includes.
In order to demonstrate the concept, let’s set up a Script Include that will hold a set of utility functions for Incidents. We’ll call it IncidentHelper.
var IncidentHelper = Class.create();
IncidentHelper.prototype = {
initialize: function () {
},
type: "IncidentHelper"
};
Now, let’s have an Incident record passed in when the class initializes and store that record to a property on the class.
var IncidentHelper = Class.create();
IncidentHelper.prototype = {
initialize: function (record) {
this.record = record;
},
type: "IncidentHelper"
};
In our initialize method, the “this” keyword refers to the instance of the IncidentHelper class.
To demonstrate what we mean, let’s create an instance of this class.
var utils = new IncidentHelper(incident);
To verify this worked, let’s log the Display Value of the record property of our instance, utils:
gs.info(utils.record.getDisplayValue());

As you can see, the “this” keyword refers to the instance of the class we’ve initialized. In this case, utils, which is an instance of the IncidentHelper class.
It even works if you want to nest function calls.
Let’s expand this a little, so that we have a function on the IncidentHelper that gets all Incidents created by the same caller.
var IncidentHelper = Class.create();
IncidentHelper.prototype = {
initialize: function (record) {
this.record = record;
this.incidentsBySameCaller = this.getIncidentsBySameCaller();
},
getIncidentsBySameCaller: function () {
// Use the record that is stored on the instance
var record = this.record;
// This array will be what we return
var incidentsBySameCaller = [];
// Look up all incidents with the same Caller that do not
// share a sys_id with the record the instance belongs to.
var incidentLookup = new GlideRecord("incident");
incidentLookup.addQuery("caller_id", record.getValue("caller_id"));
incidentLookup.addQuery("sys_id", "!=", record.getUniqueValue());
incidentLookup.query();
while (incidentLookup.next()) {
// Store the sys_id and number of the incidents
incidentsBySameCaller.push({
sys_id: incidentLookup.getUniqueValue(),
number: incidentLookup.getValue("number")
});
}
return incidentsBySameCaller;
},
type: "IncidentHelper"
};
In this example, the initialize method calls the getIncidentsBySameCaller() method using “this” to reference the instance. The getIncidentsBySameCaller() method also uses “this” to get a reference to the instance and retrieve the record property of it.
How to change “this”
What makes the “this” keyword so special is that it can be changed. In JavaScript, there are four ways to change what the “this” keyword refers to.
The call() method
The call() method allows us to set a specific “this” value for a function and call it immediately. This can be especially helpful when you want to reuse a function with different objects, without having to modify the function itself.
The ServiceNow team uses the call() method to create a pattern of Script Include classes that extend one another in order to provide a version of the Script Include that is suitable for customers to customize.
Let’s walk through an example of an actual ServiceNow Script Include that uses this method.

This Script Include, ChangeProcess was created to allow a customer to add additional functionality without having to modify the Script Include that will more likely be modified in future upgrades.
In the initialize method, call() is used to call the initialize method of the ChangeProcessSNC. The context, or “this” keyword for this execution is changed to the the instance of the ChangeProcess class. In this example, only two arguments are ever passed to the initialize method of ChangeProcessSNC because they are explicitly added in call().
Leveraging this pattern allows ServiceNow to keep all their functionality on ChangeProcessSNC protected while giving its users a place to overwrite their baseline functionality with methods of their own while remaining upgrade-proof.
The apply() method
The apply() method executes a function and changes the “this” keyword inside of that execution. Like call(), the apply() method allows us to set a specific “this” value for a function and call it immediately. However, the main difference between call() and apply() is in how they handle additional arguments.
While call() accepts arguments as a comma-separated list, apply() takes arguments as an array. This makes apply() especially useful when you’re working with a variable number of arguments or when you want to pass an array of arguments to a function.
Taking a look at an example where the ServiceNow team leverages the apply() call, and we can see they use it in a similar way to call().

This Script Include works similarly to the example in call(). By using this pattern, the ServiceNow team has provided a way for a user to add additional functionality or overwrite existing functionality without modifying the underlying ActionUtilSNC class.
In this case, apply() is better because it allows you to pass in arguments as the second parameter, so you don’t need to know every argument that could be passed in.
The bind() method
Just like call() and apply(), bind() allows us to set a specific “this” value for a function, but with a twist. Instead of immediately calling the function, bind() returns a new function with the “this” value bound to the specified object.
Let’s take our utils object with the addAllNumbers() method from earlier.
var utils = {
// For every item in an array, execute a callback
// and pass in the value of the item in the array
forEach: function (array, callback) {
var length = array.length;
for (var i = 0; i < length; i++) {
callback(array[i]);
}
},
// Add all the numbers of an array
addAllNumbers: function (numbers) {
var total = 0;
this.forEach(numbers, (number) => {
total = total + number;
});
return total;
}
};
Let’s use `bind()` to store the `addAllNumbers` method in a variable that we can call without it breaking.
var addAllNumbers = utils.addAllNumbers.bind(utils);
addAllNumbers([1,2,3,4,5]);

Now that we’ve used bind(), our addAllNumbers() variable is a bound function that will always have the utils object as its “this” keyword. Instead of being the window object, as was our issue before, when we execute our new function this time, “this” is the utils object.
ES6: Arrow functions
While ES6 is gaining traction in ServiceNow, it does have a new function expression called “Arrow functions”. One of the things that makes this this expression unique is that it does not have its own “this” binding.
This means that it will inherit the “this” of the scope that it is declared in automatically.
Let’s expand our utils object. We want to abstract the addition into another method, which we will call addNumbers(). This method will take two arguments, the numbers to add, and will return the result of adding them.
var utils = {
// For every item in an array, execute a callback
// and pass in the value of the item in the array
forEach: function (array, callback) {
var length = array.length;
for (var i = 0; i < length; i++) {
callback(array[i]);
}
},
// Add two numbers
addNumbers: function (num1, num2) {
return num1 + num2;
},
// Add all the numbers of an array
addAllNumbers: function (numbers) {
var total = 0;
this.forEach(numbers, function (number) {
total = this.addNumbers(number, total);
});
return total;
}
};
When we call the addAllNumbers() method, we get the following error.

What happened? The function we are using in the forEach() callback is not bound to an object, so its “this” keyword is the window object. In ServiceNow server-side scripting, it would be the global object.
Now let’s use an arrow function to correct this.
var utils = {
// For every item in an array, execute a callback
// and pass in the value of the item in the array
forEach: function (array, callback) {
var length = array.length;
for (var i = 0; i < length; i++) {
callback(array[i]);
}
},
// Add two numbers
addNumbers: function (num1, num2) {
return num1 + num2;
},
// Add all the numbers of an array
addAllNumbers: function (numbers) {
var total = 0;
this.forEach(numbers, (number) => {
total = this.addNumbers(number, total);
});
return total;
}
};

Here, we can see the arrow function:
this.forEach(numbers, (number) => {
total = this.addNumbers(number, total);
});
Because we are using an arrow function, the “this” keyword is used in the function.
As ServiceNow support for ES6 grows, functions like this will become available and help you write cleaner code.
In Closing
To wrap it up, remember that the “this” keyword in JavaScript the “this” keyword is a special reference to an object.
It’s like a dynamic variable that changes depending on the context of when its being used.
The most common place you’ll see “this” in ServiceNow is in Script Includes.
The call(), apply(), bind(), and arrow functions will allow you to change what the “this” keyword is bound to.
The call() and apply() methods don’t permanently change the “this” value of the function; it only sets the “this” value for that specific call.
The bind() method will return a bound function. This new function has a “this” is always the bound value.
By developing a deep understanding of the “this” keyword, you will be able to better navigate more complex situations and implement design patterns that are more advanced, allowing you to take your ServiceNow scripting to the next level.
Want to collaborate? Please get in touch.



Leave a Reply