04.11.2015 Views

javascript

Create successful ePaper yourself

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

Chapter 6: Object-Oriented Programming<br />

Object<br />

prototype<br />

Object Prototype<br />

constructor<br />

hasOwnProperty<br />

isPrototypeOf<br />

propertyIsEnumerable<br />

toLocaleString<br />

toString<br />

valueOf<br />

(function)<br />

(function)<br />

(function)<br />

(function)<br />

(function)<br />

(function)<br />

SuperType<br />

prototype<br />

SuperType Prototype<br />

__proto__<br />

constructor<br />

getSuperValue (function)<br />

SubType<br />

prototype<br />

instance<br />

__proto__<br />

subproperty false<br />

Figure 6-5<br />

SubType Prototype<br />

__proto__<br />

property<br />

true<br />

getSubValue (function)<br />

SubType inherits from SuperType , and SuperType inherits from Object . When instance.<br />

toString() is called, the method being called actually exists on Object.prototype .<br />

Prototype and Instance Relationships<br />

The relationship between prototypes and instances is discernable in two ways. The first way is to use the<br />

instanceof operator, which returns true whenever an instance is used with a constructor that appears<br />

in its prototype chain, as in this example:<br />

alert(instance instanceof Object);<br />

alert(instance instanceof SuperType);<br />

alert(instance instanceof SubType);<br />

//true<br />

//true<br />

//true<br />

Here, the instance object is technically an instance of Object , SuperType , and SubType due to the<br />

prototype chain relationship. The result is that instanceof returns true for all of these constructors.<br />

The second way to determine this relationship is to use the isPrototypeOf() method. Each prototype<br />

in the chain has access to this method, which returns true for an instance in the chain as in this example:<br />

alert(Object.prototype.isPrototypeOf(instance)); //true<br />

alert(SuperType.prototype.isPrototypeOf(instance)); //true<br />

alert(SubType.prototype.isPrototypeOf(instance)); //true<br />

172

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

Saved successfully!

Ooh no, something went wrong!