- Subscribe to RSS Feed
- Mark as New
- Mark as Read
- Bookmark
- Subscribe
- Printer Friendly Page
- Report Inappropriate Content
Yesterday I showed you how to add a method to the Dog class (see navigator links below the fold). Today I'm going to add a second method, but more importantly, I'm going to show you how to define class methods in a slightly more convenient way, using a feature of JavaScript called an object literal, also called JavaScript Object Notation (or JSON for short, pronounced JAY-sahn).
Just to be clear, before I introduce the JSON way, you could add the new class method using the same way I showed you yesterday. The JSON way is just a bit easier, with a little less cluttered code. When you start delving into the OO JavaScript that comes with our product, you'll see that we've used the JSON approach almost exclusively, just by convention.
So what is this JSON stuff? Glad you asked:
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
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.