SlightlyLoony
Tera Contributor

find_real_file.pngOn Friday, I promised (threatened?) to show you yet another way to extend a JavaScript class on the Service-now platform. This new way would let you extend a class provided by Service-now without interfering with future updates to that class, and the same mechanism would also let you make specialized versions of a class.

Our geek at right is beside himself with anticipation. Here's the answer:

Instead of modifying the GRUtil class itself (as I showed you on Friday), we're going to extend it by creating a child class of GRUtil named SpecialGRUtil. It could, of course, be named anything at all. Here's what the code looks like (in its very own script include):

var SpecialGRUtil = Class.create();

SpecialGRUtil.prototype = Object.extendsObject(GRUtil, {

/*
* Returns an array containing any tables that extend the given table. For example, given
* 'cmdb_ci_netgear', returns an array with 'cmdb_ci_ip_switch' and 'cmdb_ci_ip_router'.
*/
getChildTables: function(table) {
var om = Packages.com.glide.db.DBObjectManager.get();
var tables = om.getTableExtensions(table);
return j2js(tables);
},

type: 'SpecialGRUtil'
});


Note the special syntax Object.extendsObject(GRUtil. For now, you can think of this as a magic incantation that lets you extend an existing object (GRUtil in this case). If you're really curious how it works (and it's not really very hard), check out the script include PrototypeServer — this is where that magic incantation is actually run.

Also I've introduced one other little trick in this code, right at the end where I've put type: 'SpecialGRUtil'. This doesn't actually do anything useful in the code. Technically, it's defining a property named type containing the string 'SpecialGRUtil'. But by placing this as the very last thing defined, all the other properties being defined need a comma following them. We find it easier to remember that way. You'll see this little trick a lot in the code supplied by Service-now.

Now this code will let you use the new method:

var gru = new SpecialGRUtil();
gs.log(gru.getChildTables('cmdb_ci_server'));


It's exactly like last week, except that now you create an instance of your new class.

Now there's only one more way to extend a class to show you. This last method is useful in a special case: where you want to temporarily modify a class, so that new instantiations of it will be modified (which the first method failed to do), the class isn't permanently modified (as the second method did), and so that we don't have to create a new class as we did today. I'll show you this way tomorrow...