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.

Chapter 22: The Evolution of JavaScript<br />

extends keyword to indicate that they inherit from another class. As with other OO languages, they<br />

can only inherit from one class. Here is an example:<br />

class Person {<br />

var name: string;<br />

var age: int;<br />

}<br />

function sayName(){<br />

alert(this.name);<br />

}<br />

class Employee extends Person {<br />

var job: string;<br />

}<br />

var me = new Employee();<br />

alert(me is Person);<br />

alert(me is Employee);<br />

//true<br />

//true<br />

This code defines two classes: Person and Employee , with the latter inheriting from the former. Unlike<br />

ECMAScript 3, no additional work is necessary to ensure that the subclass inherits all properties and<br />

methods from the superclass. Additionally, extending a class ensures that instance of a subclass also<br />

has a type of the superclass, meaning that the statements me is Person and me is Employee both<br />

are true.<br />

Overriding superclass Methods<br />

To override a superclass method, you must explicitly do so using the override tag as shown in the<br />

following example. Attempting to define a method of the same name that exists in the superclass will<br />

cause an error.<br />

class Person {<br />

var name: string;<br />

var age: int;<br />

}<br />

function sayName(){<br />

alert(this.name);<br />

}<br />

class Employee extends Person {<br />

var job: string;<br />

}<br />

override function sayName(){<br />

alert(this.name + “:” + this.job);<br />

}<br />

This example overrides the sayName() method in the Employee class to output the name and job<br />

properties.<br />

731

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

Saved successfully!

Ooh no, something went wrong!