Example 9-1 demonstrates one way to define a
because it did not define a constructor. A
constructor is a function designed for the initialization of newly
created objects. Constructors are invoked using the
new keyword as described in Constructor Invocation. Constructor invocations using
new automatically create the new
object, so the constructor itself only needs to initialize the state
of that new object. The critical feature of constructor invocations is
prototype property of the
constructor is used as the prototype of the new object. This means
that all objects created with the same constructor inherit from the
same object and are therefore members of the same class. Example 9-2 shows how we could alter the range class of
Example 9-1 to use a constructor function instead of a
Example 9-2. A Range class using a constructor
// range2.js: Another class representing a range of values.
// This is a constructor function that initializes new Range objects.
// Note that it does not create or return the object. It just initializes this.
// Store the start and end points (state) of this new range object.
// These are noninherited properties that are unique to this object.
// All Range objects inherit from this object.
// Note that the property name must be "prototype" for this to work.
// Return ...