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.
var chuck = new Person(0, 0);<br />
console.log(chuck.countLimbs()); // Logs 0.<br />
<br />
Creating inheritance chains (the original intention)<br />
Prototypal inheritance was conceived to allow inheritance chains that mimic the<br />
inheritance patterns found in traditional object oriented programming languages. In<br />
order for one object to inherit from another object in <strong>JavaScript</strong>, all you have to do is<br />
instantiate an instance of the object you want to inherit from and assign it to the<br />
prototype property of the object that is doing the inheriting.<br />
In the code sample that follows, Chef objects (i.e. cody) inherit from Person(). This<br />
means that if a property is not found in a Chef object, it will then be looked for on the<br />
prototype of the function that created Person() objects. To wire up the inheritance, all<br />
you have to do is instantiate an instance of Person() as the value for Chef.prototype<br />
(i.e. Chef.prototype = new Person(); ).<br />
Sample: sample132.html<br />
<br />
var Person = function () { this.bar = 'bar' };<br />
Person.prototype.foo = 'foo';<br />
var Chef = function () { this.goo = 'goo' };<br />
Chef.prototype = new Person();<br />
var cody = new Chef();<br />
console.log(cody.foo); // Logs 'foo'.<br />
console.log(cody.goo); // Logs 'goo'.<br />
console.log(cody.bar); // Logs 'bar'.<br />
<br />
All we did in this sample was leverage a system that was already in place with the<br />
native objects. Consider that Person() is not unlike the default Object() value for<br />
prototype properties. In other words, this is exactly what happens when a prototype<br />
property, containing its default empty Object() value, looks to the prototype of the<br />
constructor function created (i.e. Object.prototype) for inherited properties.<br />
130