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