04.11.2015 Views

javascript

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 6: Object-Oriented Programming<br />

In this code, the createAnother() function accepts a single argument, which is the object to base a new<br />

object on. This object, original , is passed into the object() function, and the result is assigned to<br />

clone . Next, the clone object is changed to have a property called newProperty . The last step is to<br />

return the object. The createAnother() function can be used in the following way:<br />

var person = {<br />

name: “Nicholas”,<br />

friends: [“Shelby”, “Court”, “Van”]<br />

};<br />

var anotherPerson = createAnother(person);<br />

anotherPerson.sayHi(); //”hi”<br />

The code in this example returns a new object based on person . The anotherPerson object has all of<br />

the properties and methods of person but adds a new method called sayHi() .<br />

Parasitic inheritance is another pattern to use when you are concerned primarily with objects and not<br />

with custom types and constructors. The object() method is not required for parasitic inheritance; any<br />

function that returns a new object fits the pattern.<br />

Keep in mind that adding functions to objects using parasitic inheritance leads to<br />

inefficiencies related to function reuse, similar to the constructor pattern.<br />

Parasitic Combination Inheritance<br />

Combination inheritance is the most often - used pattern for inheritance in JavaScript, though it is not<br />

without its inefficiencies. The most inefficient part of the pattern is that the supertype constructor is<br />

always called twice: once to create the subtype ’ s prototype, and once inside the subtype constructor.<br />

Essentially, the subtype property ends up with all of the instance properties of a supertype object, only<br />

to have it overwritten when the subtype constructor executes. Consider the combination inheritance<br />

example again:<br />

function SuperType(name){<br />

this.name = name;<br />

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

}<br />

SuperType.prototype.sayName = function(){<br />

alert(this.name);<br />

};<br />

function SubType(name, age){<br />

SuperType.call(this, name);<br />

//second call to SuperType()<br />

}<br />

this.age = age;<br />

(continued)<br />

179

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

Saved successfully!

Ooh no, something went wrong!