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

determine if the prototype needs to be initialized by checking for the existence of a method that should<br />

be available. Consider this example:<br />

function Person(name, age, job){<br />

//properties<br />

this.name = name;<br />

this.age = age;<br />

this.job = job;<br />

//methods<br />

if (typeof this.sayName != “function”){<br />

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

alert(this.name);<br />

};<br />

}<br />

}<br />

var person = new Person(“Nicholas”, 29, “Software Engineer”);<br />

person.sayName();<br />

The highlighted section of code inside the constructor adds the sayName() method if it doesn ’t already<br />

exist. This block of code is executed only the first time the constructor is called. After that, the prototype has<br />

been initialized and doesn ’ t need any further modification. Remember that changes to the prototype are<br />

reflected immediately in all instances, so this approach works perfectly. The if statement may check for<br />

any property or method that will be present once initialized — there ’ s no need for multiple if statements<br />

to check each property or method; any one will do. This pattern preserves the use of instanceof in<br />

determining what type of object was created.<br />

You cannot overwrite the prototype using an object literal when using the dynamic<br />

prototype pattern. As described previously, overwriting a prototype when an<br />

instance already exists effectively cuts off that instance from the new prototype.<br />

Parasitic Constructor Pattern<br />

The parasitic constructor pattern is typically a fallback when the other patterns fail. The basic idea of this<br />

pattern is to create a constructor that simply wraps the creation and return of another object while<br />

looking like a typical constructor. Here ’ s an example:<br />

function Person(name, age, job){<br />

var o = new Object();<br />

o.name = name;<br />

o.age = age;<br />

o.job = job;<br />

o.sayName = function(){<br />

alert(this.name);<br />

(continued)<br />

167

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

Saved successfully!

Ooh no, something went wrong!