JavaScript_Succinctly
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
Instances created from a constructor function are linked to the<br />
constructor’s prototype property<br />
While it’s only an object, prototype is special because the prototype chain links every<br />
instance to its constructor function's prototype property. This means that any time an<br />
object is created from a constructor function using the new keyword (or when an object<br />
wrapper is created for a primitive value), it adds a hidden link between the object<br />
instance created and the prototype property of the constructor function used to create it.<br />
This link is known inside the instance as __proto__ (though it is only<br />
exposed/supported via code in Firefox 2+, Safari, Chrome, and Android). <strong>JavaScript</strong><br />
wires this together in the background when a constructor function is invoked, and it’s<br />
this link that allows the prototype chain to be, well, a chain. In the following sample, we<br />
add a property to the native Array() constructor’s prototype, which we can then<br />
access from an Array() instance using the __proto__ property set on that instance.<br />
Sample: sample121.html<br />
<br />
// This code only works in browsers that support __proto__ access.<br />
Array.prototype.foo = 'foo';<br />
var myArray = new Array();<br />
console.log(myArray.__proto__.foo); // Logs foo, because<br />
myArray.__proto__ = Array.prototype<br />
<br />
Since accessing __proto__ is not part of the official ECMA standard, there is a more<br />
universal way to trace the link from an object to the prototype object it inherits, and that<br />
is by using the constructor property. This is demonstrated in the following sample.<br />
Sample: sample122.html<br />
<br />
Array.prototype.foo = 'foo'; // All instances of Array() now inherit a<br />
foo property.<br />
var myArray = new Array();<br />
// Trace foo in a verbose way leveraging *.constructor.prototype<br />
console.log(myArray.constructor.prototype.foo); // Logs foo.<br />
// Or, of course, leverage the chain.<br />
console.log(myArray.foo) // Logs foo.<br />
// Uses prototype chain to find property at Array.prototype.foo<br />
123