17.11.2015 Views

JavaScript_Succinctly

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

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

sample, we take the classic Person object and mimic the pattern that <strong>JavaScript</strong> uses<br />

for inheritance.<br />

Sample: sample130.html<br />

<br />

var Person = function () { };<br />

// All Person instances inherit the legs, arms, and countLimbs<br />

properties.<br />

Person.prototype.legs = 2;<br />

Person.prototype.arms = 2;<br />

Person.prototype.countLimbs = function () { return this.legs + this.arms;<br />

};<br />

var chuck = new Person();<br />

console.log(chuck.countLimbs()); // Logs 4.<br />

<br />

In this code, a Person() constructor function is created. We then add properties to the<br />

prototype property of Person(), which can be inherited by all instances. Clearly, you<br />

can leverage the prototype chain in your code the same way that <strong>JavaScript</strong> leverages it<br />

for native object inheritance.<br />

As a good example of how you might leverage this, you can create a constructor<br />

function whose instances inherit the legs and arms properties if they are not provided<br />

as parameters. In the following sample, if the Person() constructor is sent parameters,<br />

the parameters are used as instance properties, but if one or more parameters are not<br />

provided, there is a fallback. These instance properties then shadow or mask the<br />

inherited properties, giving you the best of both worlds.<br />

Sample: sample131.html<br />

<br />

var Person = function (legs, arms) {<br />

// Shadow prototype value.<br />

if (legs !== undefined) { this.legs = legs; }<br />

if (arms !== undefined) { this.arms = arms; }<br />

};<br />

};<br />

Person.prototype.legs = 2;<br />

Person.prototype.arms = 2;<br />

Person.prototype.countLimbs = function () { return this.legs + this.arms;<br />

129

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

Saved successfully!

Ooh no, something went wrong!