↑
Main Page
Inheritance
This class defines a private property named value, which can be initialized using the class constructor. The
last function defines what happens when a plus is used with a
MyClass
object. This particular function
defines the behavior when the second operand is also a
MyClass
object: The values of the two objects are
added and a new
MyClass
object is returned. With this definition, it is possible to use the following line:
var obj1 = new MyClass(20);
var obj2 = new MyClass(30);
var obj3 = obj1 + obj2;
alert(obj3.getValue()); //outputs “50”
Finally, classes can have true static properties and methods by using the
static
keyword:
class MyClass {
public static var value : Integer = 25;
}
The static members of a class can then be accessed as you might expect:
var value : Integer = MyClass.value;
Inheritance
Inheritance in ECMAScript Edition 4 is done in the same way as in Java, by using the
extends
keyword.
For example:
class ClassA {
private var value : Integer = 0;
public function ClassA(value : Integer) {
this.value = value;
}
public function getValue() : Integer {
return this.value;
}
}
class ClassB extends ClassA {
public function ClassB(value : Integer) {
super(value);
}
public function sayValue() : Integer {
alert(this.getValue());
}
}
First, note that the
extends
keyword is used to inherit from
ClassA
to create
ClassB
. This is a much
simpler and straightforward way to establish inheritance than the traditional ECMAScript method
(although object masquerading and prototype chaining is still available for backwards compatibility).
The second thing to note is the use of the
super()
method to use
ClassA
’s constructor in
ClassB
. Once
again, this is identical to Java.
603
The Evolution of JavaScript
23_579088 ch20.qxd 3/28/05 11:44 AM Page 603
Free JavaScript Editor
Ajax Editor
©
→