18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 20<br />

As you can see, the class keyword is used to define MyClass. There is one private variable named<br />

color, one constructor, and one public method named sayColor(). In ECMAScript Edition 4, both<br />

public and private are considered namespaces that define the context in which variables and methods<br />

can be accessed. Classes defined in this manner are instantiated in the same way as in ECMAScript<br />

Edition 3, by using the new keyword:<br />

var myObject : MyClass = new MyClass();<br />

Along with variables and methods, it is possible to define getters and setters for properties. The getter is<br />

called when the variable is used for the value it contains, whereas a setter assigns a new value to a given<br />

variable.<br />

class MyClass {<br />

private var color : String = “red”;<br />

public function get myColor () {<br />

return this.color;<br />

}<br />

}<br />

public function set myColor (value : String) : Void {<br />

this.color = value;<br />

}<br />

The previous code creates a property named myColor, which can be used just like a regular property<br />

(such as color), but whose behavior is defined by the getter and setter functions. <strong>For</strong> instance:<br />

var myObject : MyClass = new MyClass();<br />

myObject.myColor = “blue”;<br />

Typically, this would be done when you want to perform some other action after a property value<br />

changes (such as changing the color of a UI element when the myColor property changes).<br />

It is also possible to redefine the behavior of operators when they interact with classes. In ECMAScript<br />

Edition 3, all operators use an object’s valueOf() or toString() method, but here it is possible for you<br />

to define exactly how a plus or minus should be used with an instance of a particular class.<br />

class MyClass {<br />

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

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

this.value = value;<br />

}<br />

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

return this.value;<br />

}<br />

}<br />

operator function “+” (anotherObject : MyClass) : MyClass {<br />

return new MyClass(this.value + anotherObject.getValue());<br />

}<br />

602

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

Saved successfully!

Ooh no, something went wrong!