↑
Main Page
MyClass
Chapter 20
As you can see, the
class
keyword is used to define
MyClass
. There is one private variable named
color
, one constructor, and one public method named
sayColor()
. In ECMAScript Edition 4, both
public
and
private
are considered
namespaces
that define the context in which variables and methods
can be accessed. Classes defined in this manner are instantiated in the same way as in ECMAScript
Edition 3, by using the
new
keyword:
var myObject : MyClass = new MyClass();
Along with variables and methods, it is possible to define getters and setters for properties. The getter is
called when the variable is used for the value it contains, whereas a setter assigns a new value to a given
variable.
class MyClass {
private var color : String = “red”;
public function get myColor () {
return this.color;
}
public function set myColor (value : String) : Void {
this.color = value;
}
}
The previous code creates a property named
myColor
, which can be used just like a regular property
(such as
color
), but whose behavior is defined by the getter and setter functions. For instance:
var myObject : MyClass = new MyClass();
myObject.myColor = “blue”;
Typically, this would be done when you want to perform some other action after a property value
changes (such as changing the color of a UI element when the
myColor
property changes).
It is also possible to redefine the behavior of operators when they interact with classes. In ECMAScript
Edition 3, all operators use an object’s
valueOf()
or
toString()
method, but here it is possible for you
to define exactly how a plus or minus should be used with an instance of a particular class.
class MyClass {
private var value : Integer = 25;
public function MyClass(value : Integer) {
this.value = value;
}
public function getValue() : Integer {
return this.value;
}
operator function “+” (anotherObject : MyClass) : MyClass {
return new MyClass(this.value + anotherObject.getValue());
}
}
602
23_579088 ch20.qxd 3/28/05 11:44 AM Page 602
Free JavaScript Editor
Ajax Editor
©
→