logo

NJP

Object-Oriented JavaScript: Literally, He Says...

Import · Aug 27, 2010 · article

Object-Oriented JavaScript:

First Steps...

A Methodical Step...

Here's my rewritten Dog class (with the script extracted from the Dog Script Include):

function Dog(name, born) { this.call_name = name; this.birth_date = born;}Dog.prototype = { 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; }}

First, note how a large block of code enclosed in curly braces ({}), defining two methods (age and birthday), is assigned to the Dog.prototype property. Those curly braces and what they enclose are an example of a JSON object literal. The syntax is very, very close to the code I showed you yesterday — but note the differences. First, in the object literal I'm not assigning a function to the age property, as I did yesterday. Instead, the JSON simply declares the age property, then there's a colon, and then the value of that property (in this case the function). After the last closing curly brace of the function definition, there's a comma (,). That's how you separate property definitions in JSON. Next the birthday method is defined, the same way that age method was defined. You can continue this same pattern to define any number of methods for a class you're building.Now let's take a look at some test script and the results:

var dog = new Dog('Miki', new Date(2006,1,11));gs.log('Hey ' + dog.call_name + '! You\'re ' + dog.age() + ' years old today!');

gs.log(dog.call_name + '\'s birthday is ' + dog.birthday());

And when I run that script, I get this:

Hey Miki! You're 4 years old today!Miki's birthday is February 11

View original source

https://www.servicenow.com/community/in-other-news/object-oriented-javascript-literally-he-says/ba-p/2286858