Prototype objects typically are not suited to define properties and methods whose values may vary
across object instances. In cases where values may vary across object instances, you typically define
those properties and methods within the class itself.
To specify the scope of a custom property or method, you define it as one of the following
four types:
•
Instance variables
•
Instance methods
•
Class variables
•
Class methods
Instance variables
Instance variables are any variables (properties) that are defined in a constructor function and that
are copied into each object instance of that constructor. All object instances have their own copies
of instance variables. This means that if there are five object instances of a
five copies of each instance variable defined in the class. Because each object instance has its own
copy of an instance variable, each object instance can assign a unique value to an instance variable
without modifying the values of other copies of the instance variable. You access instance variables
directly from their containing object instances.
The following example defines four instance variables—
constructor function. These four instance variables are available directly from all object instances
of the
constructor.
Car
function Car(make, model, color) { // define a Car class
this.make = make;
this.model = model;
this.color = color;
this.speed = 0;
}
The following object instance
the instance variable
whose initial value is 0 because the
// objCar.make="Subaru", objCar.model="Forester",
// objCar.color="silver", objCar.speed = 0
var objCar = new Car("Subaru", "Forester", "silver");
Instance methods
Instance methods are any methods that are accessible through an object instance. Object instances
do not have their own copies of instance methods. Instead, instance methods are first defined as
functions, and then properties of the constructor function's prototype object are set to the
function values. Instance methods use the keyword
function to refer to the object instance they are operating on. Although a given object instance
does not have a copy of an instance method, you still access instance methods directly from their
associated object instances.
contains all four instance variables. Although a value for
objCar
is not passed to the
speed
variable is defined in the
speed
Object-oriented programming with JavaScript syntax
,
,
make
model
constructor,
Car
objCar
Car
in the body of the defining constructor
this
class, there are
Circle
, and
—in a
color
speed
still has a
property
speed
constructor.
69
Need help?
Do you have a question about the DIRECTOR MX 2004-DIRECTOR SCRIPTING and is the answer not in the manual?
Questions and answers