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

(continued)<br />

}<br />

};<br />

return o;<br />

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

person.sayName(); //”Nicholas”<br />

In this example, the Person constructor creates a new object, initializes it with properties and methods,<br />

and then returns the object. This is exactly the same as the factory pattern except that the function is<br />

called as a constructor, using the new operator. When a constructor doesn ’ t return a value, it returns the<br />

new object instance by default. Adding a return statement at the end of a constructor allows you to<br />

override the value that is returned when the constructor is called.<br />

This pattern allows you to create constructors for objects that may not be possible otherwise. For<br />

example, you may want to create a special array that has an extra method. Since you don ’ t have direct<br />

access to the Array constructor, this pattern works:<br />

function SpecialArray(){<br />

//create the array<br />

var values = new Array();<br />

//add the values<br />

values.push.apply(values, arguments);<br />

//assign the method<br />

values.toPipedString = function(){<br />

return this.join(“|”);<br />

};<br />

}<br />

//return it<br />

return values;<br />

var colors = new SpecialArray(“red”, “blue”, “green”);<br />

alert(colors.toPipedString()); //”red|blue|green”<br />

In this example, a constructor called SpecialArray is created. In the constructor, a new array is created<br />

and initialized using the push() method (which has all of the constructor arguments passed in). Then a<br />

method called toPipedString() is added to the instance, which simply outputs the array values as a<br />

pipe - delimited list. The last step is to return the array as the function value. Once that is complete, the<br />

SpecialArray constructor can be called, passing in the initial values for the array, and<br />

toPipedString() can be called.<br />

A few important things to note about this pattern: There is no relationship between the returned object<br />

and the constructor or the constructor ’ s prototype; the object exists just as if it were created outside of a<br />

constructor. Therefore, you cannot rely on the instanceof operator to indicate the object type. Due to<br />

these issues, this pattern should not be used when other patterns work.<br />

168

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

Saved successfully!

Ooh no, something went wrong!