Consider the following code:
function rectangle(x, y) {
this.width = x;
this.height = y;
this.calcArea = function() {
return (this.width * this.height);
};
}
The rectangle
object has two properties (width and height) and one method (calcArea).
I wish to add another property to the rectangle object: area
. I will do this through the prototype method, like so:
rectangle.prototype.area = function () {return this.calcArea();}
Imagine now that we create a new instance of rectangle: var r = new rectangle(2,3);
Unfortunately, area
is a method. To retrieve the correct value you must call r.area();
Since area
should be (semantically, at least) a property and not a method, is there a way to directly assign the result of calcArea()
to the r.area
property?
If I change the prototype to this:
rectangle.prototype.area = function () {this.area = this.calcArea();}
I have to call r.area()
once, and then all subsequent calls to r.area
will be a number, as desired. It's not bad, but it's not perfect. So is there a better way?