17.11.2015 Views

JavaScript_Succinctly

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

In this example, the foo property is found within the prototype object. You need to<br />

realize this is only possible because of the association between the instance of Array()<br />

and the Array() constructor prototype object (i.e. Array.prototype). Simply put,<br />

myArray.__proto__ (or myArray.constructor.prototype) references<br />

Array.prototype.<br />

Last stop in the prototype chain is Object.prototype<br />

Since the prototype property is an object, the last stop in the prototype chain or lookup<br />

is at Object.prototype. In the code that follows, I create myArray, which is an empty<br />

array. I then attempt to access a property of myArray that has not yet been defined,<br />

engaging the prototype lookup chain. The myArray object is examined for the foo<br />

property. Being absent, the property is looked for at Array.prototype, but it is not<br />

there either. So the final place <strong>JavaScript</strong> looks is Object.prototype. Because it is not<br />

defined in any of those three objects, the property is undefined.<br />

Sample: sample123.html<br />

<br />

var myArray = [];<br />

console.log(myArray.foo) // Logs undefined.<br />

/* foo was not found at myArray.foo or Array.prototype.foo or<br />

Object.prototype.foo, so it is undefined. */<br />

<br />

Take note that the chain stopped with Object.prototype. The last place we looked for<br />

foo was Object.prototype.<br />

Notes<br />

Careful! Anything added to Object.prototype will show up in a for in loop.<br />

The prototype chain returns the first property match it finds in the<br />

chain<br />

Like the scope chain, the prototype chain will use the first value it finds during the<br />

chain lookup.<br />

124

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

Saved successfully!

Ooh no, something went wrong!