Had you kept your money under the mattress instead of investing it, would you have more now or less? How much more or less?
GreaterThanZero.com


Page 3 of: Object-Oriented Programming in JavaScript Explained, by Thomas Becker   about me  

Class-Based OOP: A Simple Class Defintion

Let's look at a simple example of a class definition. The code below is Java, but if you're familiar with just any class-based OO language, you'll be able to make sense of it.
class Point {

  // x- and y-coordinate
  private double x;
  private double y;

  // Constructor from coordinates
  public Point(double x, double y) {
    this.x = x;
    this.y = y;
  }

  // Distance between this and another point
  public double distance(Point other) {
    return Math.sqrt(Math.pow(this.x - other.x, 2) +
      Math.pow(this.y - other.y, 2));
  }

  // Get label, like "(1.00, -1.00)"
  public String getLabel() {
    DecimalFormat coordinateFormatter = new DecimalFormat("#.##");
    return new StringBuilder("(")
      .append(coordinateFormatter.format(x))
      .append(", ")
      .append(coordinateFormatter.format(y))
      .append(")").toString();
  }
}
The following line of Java code instantiates this class, that is, it creates a Point object:
Point p = new Point(0.0, 0.0);
The expression on the right hand side does three things. It
  • creates a new Point object,
  • calls the constructor, which intializes the fields (member variables),
  • then returns the newly created and initialized object.

In languages other than Java, the line may look a tad different, but the basic principle remains the same. In the next two sections, we'll explore the JavaScript equivalent of all this.