Pages

Extending standard classes

We have another change request of our toy blog manager. The user is happy with the signature we added at the end of each post, but he is not so happy with the format we are using to display the post date. He wants it to be showed in an his own specific format.

This is quite a nuisance 'cause we can't use a standard method but we have to create a brand new one. On the other side it is very easy to add a custom method to an existing class (even a standard one): it is just a matter of adding a new function to the prototype object of the class.

Here what we do for customizing Date:

Date.prototype.shortFormat = function() {
return this.getDate() + "/" + this.getMonth() + "/" + this.getFullYear();
}

Now we can call shortFormat() from any date objects in our code:

BlogEntry.prototype.toHTML = function() {
return "<b><i>(" + this.date.shortFormat() + ")</i> " + this.title +
"</b><br />" + this.body + "<br /><i>" + this.signature +"</i>";
}

More information on custom objects in chapter ten of Head First JavaScript.

No comments:

Post a Comment