Assigning methods to prototype

We have implemented a simple JavaScript class defining a few methods in the constructor. There is a better way of doing it, using the prototype property.

Every class has its own property property, that is a sort of blueprint used to create a new object of that kind. So, instead of creating a different instance of the same method for each instantiated object, we can have a unique method for each instance of that class.

To get this result we rearrange the code in this way:

function BlogEntry(title, body, date) {
this.title = title;
this.body = body;
this.date = (typeof(date) == "undefined" || date == null) ? new Date() : date;
}

BlogEntry.prototype.toString = function() {
return this.title + " (" + this.date.toDateString() + "): " + this.body;
}

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


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

No comments:

Post a Comment