Class properties

We have just seen that makes sense putting the method definition in the prototype property of a class, and now it comes natural to us asking: and what about properties?

It could make sense too. But only if you really need that the same piece of information is shared among all the objects of that kind.

Let's say we want to show a signature at the end of each post in our simple blog. The signature should be the same for all the posts, so in this case it makes sense to have it defined as class property. Curiosly enough, even though a class property is not related with a single instance of the class, when we want to access it from a class method we have to qualify it by using "this". It is kind of obvious, though, if we think that it is actually stored in the prototype property, that is accessed as a normal property in a object.

In the coding of the class this resolves in adding the definition of the signature property and using it in the required methods:

BlogEntry.prototype.signature = "The blog owner";

BlogEntry.prototype.toHTML = function() {
return "<b><i>(" + + ")</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