06.07.2017 Views

Mastering JavaScript

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

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

Object-Oriented <strong>JavaScript</strong><br />

To have a side effect-free and accurate inheritance mechanism, we have to make sure<br />

that we perform the following:<br />

• Setting the prototype to an instance of the parent initializes the prototype<br />

chain (inheritance); this is done only once (as the prototype object is shared)<br />

• Calling the parent's constructor initializes the object itself; this is done<br />

with every instantiation (you can pass different parameters each time you<br />

construct it)<br />

With this understanding in place, let's define the rest of the objects:<br />

function IndividualContributor() {<br />

Employee.call(this);<br />

this.active_projects = [];<br />

}<br />

IndividualContributor.prototype = Object.create(Employee.prototype);<br />

function TeamLead() {<br />

Manager.call(this);<br />

this.dept = "Software";<br />

this.salary = 100000;<br />

}<br />

TeamLead.prototype = Object.create(Manager.prototype);<br />

function Engineer() {<br />

TeamLead.call(this);<br />

this.dept = "<strong>JavaScript</strong>";<br />

this.desktop_id = "8822" ;<br />

this.salary = 80000;<br />

}<br />

Engineer.prototype = Object.create(TeamLead.prototype);<br />

Based on this hierarchy, we can instantiate these objects:<br />

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

console.log(genericEmployee);<br />

You can see the following output for the preceding code snippet:<br />

[object Object] {<br />

dept: "None",<br />

name: "",<br />

salary: 0<br />

}<br />

[ 114 ]<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!