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

The object() function creates a temporary constructor, assigns a given object as the constructor ’ s<br />

prototype, and returns a new instance of the temporary type. Essentially, object() performs a shadow<br />

copy of any object that is passed into it. Consider the following:<br />

var person = {<br />

name: “Nicholas”,<br />

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

};<br />

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

anotherPerson.name = “Greg”;<br />

anotherPerson.friends.push(“Rob”);<br />

var yetAnotherPerson = object(person);<br />

yetAnotherPerson.name = “Linda”;<br />

yetAnotherPerson.friends.push(“Barbie”);<br />

alert(person.friends);<br />

//”Shelby,Court,Van,Rob,Barbie”<br />

This is the way Crockford advocates using prototypal inheritance: You have an object that you want to<br />

use as the base of another object. That object should be passed into object(), and the resulting object<br />

should be modified accordingly. In this example, the person object contains information that should be<br />

available on another object, so it is passed into the object() function, which returns a new object. The<br />

new object has person as its prototype, meaning that it has both a primitive value property and a<br />

reference value property on its prototype. This also means that person.friends is shared not only by<br />

person , but also with anotherPerson and yetAnotherPerson . Effectively, this code has created two<br />

clones of person .<br />

Prototypal inheritance is useful when there is no need for the overhead of creating separate constructors<br />

but you still need an object to behave similarly to another. Keep in mind that properties containing<br />

reference values will always share those values, similar to using the prototype pattern.<br />

Parasitic Inheritance<br />

Closely related to prototypal inheritance is the concept of parasitic inheritance, another pattern popularized<br />

by Crockford. The idea behind parasitic inheritance is similar to that of the parasitic constructor and factory<br />

patterns: create a function that does the inheritance, augments the object in some way, and then returns the<br />

object as if it did all the work. The basic parasitic inheritance pattern looks like this:<br />

function createAnother(original){<br />

var clone = object(original);<br />

clone.sayHi = function(){<br />

alert(“hi”);<br />

};<br />

return clone;<br />

}<br />

//create a new object by calling a function<br />

//augment the object in some way<br />

//return the object<br />

178

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

Saved successfully!

Ooh no, something went wrong!