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.

console.log(FooInstance.constructor === Foo); // Logs false, we broke the<br />

reference.<br />

console.log(FooInstance.constructor); // Logs Object(), not Foo()<br />

// Compare to code in which we do not replace the prototype value.<br />

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

var BarInstance = new Bar();<br />

console.log(BarInstance.constructor === Bar); // Logs true.<br />

console.log(BarInstance.constructor); // Logs Bar()<br />

<br />

If you intend to replace the default prototype property (common with some JS OOP<br />

patterns) set up by <strong>JavaScript</strong>, you should wire back together a constructor property<br />

that references the constructor function. In the following sample, we alter our previous<br />

code so that the constructor property will again provide a reference to the proper<br />

constructor function.<br />

Sample: sample126.html<br />

<br />

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

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

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

console.log(FooInstance.constructor === Foo); // Logs true.<br />

console.log(FooInstance.constructor); // Logs Foo()<br />

<br />

Instances that inherit properties from prototype will always get the<br />

latest values<br />

The prototype property is dynamic in the sense that instances will always get the latest<br />

value from the prototype regardless of when it was instantiated, changed, or appended.<br />

In the code that follows, we create a Foo constructor, add the property x to the<br />

prototype, and then create an instance of Foo() named FooInstance. Next, we log<br />

the value of x. Then we update the prototype’s value of x and log it again to find that our<br />

instance has access to the latest value found in the prototype object.<br />

126

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

Saved successfully!

Ooh no, something went wrong!