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 />

In this example, the SuperType constructor defines a property colors that contains an array<br />

(a reference value). Each instance of SuperType has its own colors property containing its own array.<br />

When SubType inherits from SuperType via prototype chaining, SubType.prototype becomes an<br />

instance of SuperType and so it gets its own colors property, which is akin to specifically creating<br />

SubType.prototype.colors . The end result: all instances of SubType share a colors property. This is<br />

indicated as the changes made to instance1.colors are reflected on instance2.colors .<br />

A second issue with prototype chaining is that you cannot pass arguments into the supertype constructor<br />

when the subtype instance is being created. In fact, there is no way to pass arguments into the supertype<br />

constructor without affecting all of the object instances. Due to this and the aforementioned issue with<br />

reference values on the prototype, prototype chaining is rarely used alone.<br />

Constructor Stealing<br />

In an attempt to solve the inheritance problem with reference values on prototypes, developers began<br />

using a technique called constructor stealing (also sometimes called object masquerading or classical<br />

inheritance). The basic idea is quite simple: call the supertype constructor from within the subtype<br />

constructor. Keeping in mind that functions are simply objects that execute code in a particular context,<br />

the apply() and call() methods can be used to execute a constructor on the newly created object, as in<br />

this example:<br />

function SuperType(){<br />

this.colors = [“red”, “blue”, “green”];<br />

}<br />

function SubType(){<br />

//inherit from SuperType<br />

SuperType.call(this);<br />

}<br />

var instance1 = new SubType();<br />

instance1.colors.push(“black”);<br />

alert(instance1.colors); //”red,blue,green,black”<br />

var instance2 = new SubType();<br />

alert(instance2.colors); //”red,blue,green”<br />

The highlighted lines in this example show the single call that is used in constructor stealing. By<br />

using the call() method (or alternately, apply() ), the SuperType constructor is called in the context<br />

of the newly created instance of SubType . Doing this effectively runs all of the object-initialization code<br />

in the SuperType() function on the new SubType object. The result is that each instance has its own<br />

copy of the colors property.<br />

175

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

Saved successfully!

Ooh no, something went wrong!