Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

SlightlyLoony
Tera Contributor

find_real_file.pngIf you've been following along on these object-oriented JavaScript posts, then you should already know quite a bit about JavaScript classes and objects. But wait — there's more!

Today I'm going to talk about class properties. As the name implies, these are properties associated with a class, as opposed to an instance. You already know about one of these: the special class property called prototype. But you can also use class properties for other things, including both values and functions (methods).

The classic use for a class property is for a getter method: a class method that returns an instance. And a classic use for a value class property is to hold a collection of instances. Here's an example of both:


First, I slightly revised the Dog script include:

function Dog(name, born) {
this.call_name = name;
this.birth_date = born;
Dog.byName[name] = this;
}

Dog.byName = {};

Dog.getByName = function(name) {
return Dog.byName[name];
}

Dog.prototype = {
taxon: 'Canis lupus familiaris',

age: function() {
var dog_age_ms = new Date().getTime() - this.birth_date.getTime();
var dog_age_days = dog_age_ms / (1000 * 60 * 60 * 24);
var dog_age_years = Math.floor(dog_age_days / 365.25);
return dog_age_years;
},

birthday: function() {
var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July',
'August', 'September', 'October', 'November', 'December'];
var month = this.birth_date.getMonth();
var day = this.birth_date.getDate();
return months[month] + ' ' + day;
}
}

There are three additions here:
  1. Class property byName: This is a value property, initialized to an Object instance with no properties. This will be used to hold a collection of Dog instances organized by the call name of the dog.
  2. Class method getByName(name): This is a function property, creating a class method. Given a dog's call name, this method will retrieve the corresponding Dog instance from the byName collection.
  3. Constructor adds to collection: Each time a Dog instance is constructed, this line of code will add it to the byName collection.

Here's some test code...

new Dog('Miki', new Date(2006,1,11));
new Dog('Lea', new Date(1997,9,16));
new Dog('Mo\'i', new Date(2001,3,26));

var moi = Dog.getByName('Mo\'i');
gs.log('Mo\'i is ' + moi.age() + ' years old now.');

...to illustrate how it all works:

Mo'i is 9 years old now.

Note: if you're wondering why the name "Mo'i" has an apostrophe in it, it's because his name is Hawaiian, and in the written form of that language an apostrophe represents a glottal stop, similar to the hyphen in "uh-oh". His name is pronounced MO-ee...