DekGenius.com
[ Team LiB ] Previous Section Next Section

Recipe 12.7 Defining Read-Only Properties

12.7.1 Problem

You want to create a read-only property for a class.

12.7.2 Solution

Use the addProperty( ) method in the constructor and pass it a null value for the setter method.

12.7.3 Discussion

There are at least two good reasons to have read-only properties:

  • You want to create constants for your class.

  • You want to have a dependent property whose value depends on other properties/factors.

The addProperty( ) method creates getter/setter properties for a class. Passing addProperty( ) a null value for the setter method parameter effectively creates a read-only property.

See Recipe 12.6 for the initial implementation of the Square class. Here is a modified version:

_global.Square = function (side) {
  this.side = side;

  // Create a read-only property, version (effectively, a constant). The getter
  // method is getVersion(  ). The setter method is null.
  this.addProperty("version", this.getVersion, null);

  // Create a dependent property, area (its value changes, so it is not a constant,
  // but the value depends on other property values and can't be set directly). The
  // getter method is getArea(  ). The setter method is null.
  this.addProperty("area", this.getArea, null);
};

Square.prototype.getArea = function (  ) {
  return Math.pow(this.side, 2);
};

Square.prototype.getVersion = function (  ) {
  // Always returns the string "1.0". Therefore, it is a constant.
  return "1.0";
};

// Create a square with a side length of 5.
sq = new Square(5);
trace(sq.area);        // Displays: 25

// Try to set area directly. This is a read-only property. Though no error is
// displayed, it does not set the area.
sq.area = 36;

// Check the area again.
trace(sq.area);       // Displays: 25  (because area is not changed)

// Set the side property.
sq.side = 10;
trace(sq.area);       // Displays: 100 (dependent on the value of side)
trace(sq.version);    // Displays: 1.0

// Try to set version. It is a constant, so it will not be overwritten.
sq.version = "version 2.0";
trace(sq.version);    // Displays: 1.0

12.7.4 See Also

Recipe 12.6

    [ Team LiB ] Previous Section Next Section