SlightlyLoony
Tera Contributor

find_real_file.pngYesterday I threatened to show you one way to extend a JavaScript class. This is done a bit differently than how the woman at right has extended her hair.

We're going to extend GRUtil to add a new method: getChildTables(). This method will return all the child classes of the given class, so that we can write code like this:


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


That code should log:

cmdb_ci_osx_server,cmdb_ci_mainframe,cmdb_ci_linux_server,cmdb_ci_unix_server,
cmdb_ci_aix_server,cmdb_ci_hpux_server,cmdb_ci_solaris_server,cmdb_ci_esx_server,
cmdb_ci_netware_server,cmdb_ci_win_server,cmdb_ci_mainframe_lpar


Which are all the classes that extend cmdb_ci_server in the out-of-the-box product. The code to implement that method (or function) looks like this:


getChildTables: function(table) {
var om = Packages.com.glide.db.DBObjectManager.get();
var tables = om.getTableExtensions(table);
return j2js(tables);
}


But how do we add that code to our GRUtil class? Here's the first (of four) ways that I'm going to show you:

var gru = new GRUtil();

gru.getChildTables = function(table) {
var om = Packages.com.glide.db.DBObjectManager.get();
var tables = om.getTableExtensions(table);
return j2js(tables);
};

gs.log(gru.getChildTables('cmdb_ci_server'));


The first line of this code just creates a GRUtil instance and initializes the gru variable to it. The second line extends the gru object — the object, not the class. The third line actually uses our new method.

Why did I make the distinction between object and class above? Consider this code:

var gru = new GRUtil();

gru.getChildTables = function(table) {
var om = Packages.com.glide.db.DBObjectManager.get();
var tables = om.getTableExtensions(table);
return j2js(tables);
};

gs.log(gru.getChildTables('cmdb_ci_server'));

var gru2 = new GRUtil();
gs.log(gru2.getChildTables('cmdb_ci_server'));


You might think the last two lines would log the same tables as the before them. Instead, they log undefined. What's going on?

The extension we made in the second line of that code only applied to the GRUtil object in the gru variable. When we created a new instance of GRUtil to put into gru2, that new instance did not include our extension. When we tried to invoke that extension in the last line of code, it was undefined — and that's what we logged.

This method of object extension is useful when you have some reason to temporarily extend the object, and you don't want the extension to apply to other places the object is used. It's much more common to want to extend the object everywhere, for all uses of it. In the example I'm using here, that is the case: getChildTables() is a potentially useful method anywhere at all. So that means that today I showed you the wrong technique for our need. Tomorrow I'll show you a more appropriate way...