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.

Providing a new object as the prototype property does not update the connection<br />

between instances already created and the new prototype.<br />

But remember, as I stated previously, you can update or add to the originally created<br />

prototype object and those values remain connected to the first instance(s).<br />

Sample: sample129.html<br />

<br />

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

Foo.prototype.x = 1;<br />

var FooInstance = new Foo();<br />

console.log(FooInstance.x); // Logs 1, as you think it would.<br />

// Now let’s replace/override the prototype object with a new Object()<br />

object.<br />

Foo.prototype = { x: 2 };<br />

console.log(FooInstance.x); // Logs 1. WHAT? Shouldn't it log 2 because<br />

we just updated prototype?<br />

/* FooInstance still references the same state of the prototype object<br />

that was there when it was instantiated. */<br />

// Create a new instance of Foo()<br />

var NewFooInstance = new Foo();<br />

// The new instance is now tied to the new prototype object value (i.e.<br />

{x:2};).<br />

console.log(NewFooInstance.x); // Logs 2.<br />

<br />

The key idea to take away here is that an object’s prototype should not be replaced with<br />

a new object once you start creating instances. Doing so will result in instances that<br />

have a link to different prototypes.<br />

User-defined constructors can leverage the same prototype<br />

inheritance as native constructors<br />

Hopefully at this point in the chapter, it is sinking in how <strong>JavaScript</strong> itself leverages the<br />

prototype property for inheritance (e.g., Array.prototype). This same pattern can be<br />

leveraged when creating non-native, user-defined constructor functions. In the following<br />

128

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

Saved successfully!

Ooh no, something went wrong!