04.11.2015 Views

javascript

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

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

Class Prototypes<br />

Chapter 22: The Evolution of JavaScript<br />

You can force a method to be declared on the prototype, and therefore shared amongst instances, by<br />

using the prototype attribute as shown here:<br />

class Person {<br />

}<br />

//private properties<br />

private var personName: String;<br />

private var personAge: Number;<br />

//constructor<br />

function Person(name: string, age: int){<br />

personName = name;<br />

personAge = age;<br />

}<br />

//public function<br />

prototype function sayAge(){<br />

alert(personAge);<br />

}<br />

This modification defines the sayAge() method on Person.prototype instead of creating a new<br />

version for each instance. The instances of Person all have access to sayAge() on the prototype and<br />

will benefit from its use of the this object for late binding of the object being used.<br />

Virtual Properties<br />

Virtual properties are defined by providing getters and/or setters for a specific property name. Instead<br />

of being a true property, which simply stores data, virtual properties may perform some additional<br />

processing when the property is accessed before determining an action to take. Getters and setters are<br />

defined via function get and function set as part of the class definition, as shown in this example:<br />

class Person {<br />

//private properties<br />

private var personName: String;<br />

private var personAge: Number;<br />

//constructor<br />

function Person(name: string, age: int){<br />

personName = name;<br />

personAge = age;<br />

}<br />

//name property<br />

function get name(): string{<br />

return personName;<br />

(continued)<br />

727

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

Saved successfully!

Ooh no, something went wrong!