JavaScript_Succinctly
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
een defined. You might think that because myArray.foo is not a property of the<br />
myArray object, <strong>JavaScript</strong> will immediately return undefined. But <strong>JavaScript</strong> will look<br />
in two more places (Array.prototype and then Object.prototype) for the value of<br />
foo before it returns undefined.<br />
Sample: sample37.html<br />
<br />
var myArray = [];<br />
console.log(myArray.foo); // Logs undefined.<br />
/* JS will look at Array.prototype for Array.prototype.foo, but it is not<br />
there. Then it will look for it at Object.prototype, but it is not there<br />
either, so undefined is returned! */<br />
<br />
When I attempt to access a property of an object, it will check that object instance for<br />
the property. If it has the property, it will return the value of the property, and there is no<br />
inheritance occurring because the prototype chain is not leveraged. If the instance does<br />
not have the property, <strong>JavaScript</strong> will then look for it on the object's constructor function<br />
prototype object.<br />
All object instances have a property that is a secret link (aka __proto__) to the<br />
constructor function that created the instance. This secret link can be leveraged to grab<br />
the constructor function, specifically the prototype property of the instance’s constructor<br />
function.<br />
This is one of the most confusing aspects of objects in <strong>JavaScript</strong>. But let's reason this<br />
out. Remember that a function is also an object with properties. It makes sense to allow<br />
objects to inherit properties from other objects. Just like saying: "Hey object B, I would<br />
like you to share all the properties that object A has." <strong>JavaScript</strong> wires this all up for<br />
native objects by default via the prototype object. When you create your own<br />
constructor functions, you can leverage prototype chaining as well.<br />
How exactly <strong>JavaScript</strong> accomplishes this is confusing until you see it for what it is: just<br />
a set of rules. Let's create an array to examine the prototype property closer.<br />
Sample: sample38.html<br />
<br />
// myArray is an Array object.<br />
var myArray = ['foo', 'bar'];<br />
52