User Guide
Object-oriented programming with JavaScript syntax 71
The following example defines a function named setInitialSpeed() that can change the
default speed of new car instances. The function name is assigned to the
setInitialSpeed
property of the
Car class.
function Car(make, model, color) { // define a Car class
this.make = make;
this.model = model;
this.color = color;
this.speed = Car.defaultSpeed;
}
Car.defaultSpeed = 10; // initial speed for new Car instances
// increase the speed of a Car
function Car_setInitialSpeed(x) {
Car.defaultSpeed = x;
}
Car.setInitialSpeed = Car_setInitialSpeed;
You access the setInitialSpeed() class method directly from the Car class.
var newSpeed = Car.setInitialSpeed(30);
You can also create a class method by using function literal syntax. The following example uses
function literal syntax to define a
setInitialSpeed() method that contains the same
functionality as the
setInitialSpeed() function defined previously.
// increase the speed of a Car
Car.setInitialSpeed = function(x) {
Car.defaultSpeed = x;
}
Recommended steps for defining a class
The following list describes the recommended steps to follow when defining a class:
1 Define a constructor function that is used as the template from which all object instances are
initialized. You may additionally define any instance variables in the constructor function by
using the keyword
this to refer to an object instance.
2 Define any instance methods, and possibly additional instance variables, that are stored in the
prototype object of a class. These instance methods and variables are available to all object
instances, and are accessible through the prototype object of the class.
3 Define any class methods, class variables, and constants that are stored in the class itself. These
class methods and variables are accessible only through the class itself.
In your code, when you access a property of an object instance, JavaScript syntax searches the
object instance itself for that property. If the instance does not contain the property, JavaScript
syntax then searches the prototype object of the super-class from which the instance was created.
Because an object instance is searched before the prototype object of the class from which it was
created, object instance properties essentially hide properties from the prototype object of their
super-classes. This means that both an object instance and its super-class could realistically define
a property with the same name but different values.