logo

NJP

Object-Oriented JavaScript: Classy Properties...

Import · Sep 01, 2010 · article

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...

View original source

https://www.servicenow.com/community/in-other-news/object-oriented-javascript-classy-properties/ba-p/2286765