18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

The Evolution of <strong>JavaScript</strong><br />

This class defines a private property named value, which can be initialized using the class constructor. The<br />

last function defines what happens when a plus is used with a MyClass object. This particular function<br />

defines the behavior when the second operand is also a MyClass object: The values of the two objects are<br />

added and a new MyClass object is returned. With this definition, it is possible to use the following line:<br />

var obj1 = new MyClass(20);<br />

var obj2 = new MyClass(30);<br />

var obj3 = obj1 + obj2;<br />

alert(obj3.getValue()); //outputs “50”<br />

Finally, classes can have true static properties and methods by using the static keyword:<br />

class MyClass {<br />

public static var value : Integer = 25;<br />

}<br />

The static members of a class can then be accessed as you might expect:<br />

var value : Integer = MyClass.value;<br />

Inheritance<br />

Inheritance in ECMAScript Edition 4 is done in the same way as in Java, by using the extends keyword.<br />

<strong>For</strong> example:<br />

class ClassA {<br />

private var value : Integer = 0;<br />

}<br />

public function ClassA(value : Integer) {<br />

this.value = value;<br />

}<br />

public function getValue() : Integer {<br />

return this.value;<br />

}<br />

class ClassB extends ClassA {<br />

}<br />

public function ClassB(value : Integer) {<br />

super(value);<br />

}<br />

public function sayValue() : Integer {<br />

alert(this.getValue());<br />

}<br />

First, note that the extends keyword is used to inherit from ClassA to create ClassB. This is a much<br />

simpler and straightforward way to establish inheritance than the traditional ECMAScript method<br />

(although object masquerading and prototype chaining is still available for backwards compatibility).<br />

The second thing to note is the use of the super() method to use ClassA’s constructor in ClassB. Once<br />

again, this is identical to Java.<br />

603

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!