Check if a JS object is exactly from type x

jan80
Tera Contributor

Hi everyone!

 

I need to check the exact type of an object, without going up the prototype chain.

 

For example, if I want to know if a given object is from type GlideDateTime, the approach of using instanceof wouldn't be sufficient:

var t = new GlideDate();
gs.addInfoMessage(t instanceof GlideDateTime);
// true

 

One possible solution to solve this problem would be to check the constructor attribute like in the next two examples:

var o = new String();
gs.addInfoMessage(o.constructor.name);
// String
function Testtt() {}
var f = new Testtt();
gs.addInfoMessage(f.constructor.name);
// Testtt

 

But for some reason this doesn't work in ServiceNow:

var t = new GlideDate();
gs.addInfoMessage(t.constructor.name);
// undefined

 

So I was wondering, is there a way to accomplish this in ServiceNow?

1 REPLY 1

Slava Savitsky
Giga Sage

In the base system, there is script include called JSUtil, which (among other utility functions) has instance_of method that works for both Java and JavaScript classes. Here is the code of that function:

JSUtil.instance_of = function(item, klass) {
	
	if (JSUtil._isString(klass)) {
		item = GlideRhinoHelper.getNativeFromRhino(item);
		if (JSUtil.isJavaObject(item))		
			return GlideJSUtil.isInstanceOf(item, klass);
		
		return false;  
	}
	
	return item instanceof klass;
};

 

However, it also returns true if you test a GlideDate object against the GlideDateTime class:

var gd = new GlideDate();
gs.print(JSUtil.instance_of(gd, GlideDate));		// true
gs.print(JSUtil.instance_of(gd, GlideDateTime));	// true

 

Most likely, GlideDate is an extension of GlideDateTime. Therefore, all GlideDate objects are instances of both classes. However, if you test a GlideDateTime object, it only belongs to the GlideDateTime class, but not to GlideDate:

var gdt = new GlideDateTime();
gs.print(JSUtil.instance_of(gdt, GlideDate));		// false
gs.print(JSUtil.instance_of(gdt, GlideDateTime));	// true

 

So there is nothing wrong in your code. You simply need to check against both classes in order to determine if your object is a GlideDate or a GlideDateTime. The same applies to other situations where you deal with class extension.