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

resolves to person.name . Early JavaScript developers used this pattern frequently to create new objects.<br />

There was an obvious downside to this approach: creating multiple objects with the same interface<br />

requires a lot of code duplication. To solve this problem, developers began using a variation of the<br />

factory pattern.<br />

The Factory Pattern<br />

The factory pattern is a well - known design pattern used in software engineering to abstract away the<br />

process of creating specific objects (other design patterns and their implementation in JavaScript are<br />

discussed later in the book). With no way to define classes in ECMAScript, developers created functions<br />

to encapsulate the creation of objects with specific interfaces, such as in this example:<br />

function createPerson(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 />

};<br />

return o;<br />

}<br />

var person1 = createPerson(“Nicholas”, 29, “Software Engineer”);<br />

var person2 = createPerson(“Greg”, 27, “Doctor”);<br />

Here, the function createPerson() accepts arguments with which to build an object with all of the<br />

necessary information to represent a Person object. The function can be called any number of times with<br />

different arguments and will still return an object that has three properties and one method. Though this<br />

solved the problem of creating multiple similar objects, the factory pattern didn ’ t address the issue of object<br />

identification (what type of object an object is). As JavaScript continued to evolve, a new pattern emerged.<br />

The Constructor Pattern<br />

As mentioned in previous chapters, constructors in ECMAScript are used to create specific types of<br />

objects. There are native constructors, such as Object and Array , which are available automatically in<br />

the execution environment at runtime. It is also possible to define custom constructors that define<br />

properties and methods for your own type of object. For instance, the previous example can be rewritten<br />

using the constructor pattern as the following:<br />

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

this.name = name;<br />

this.age = age;<br />

this.job = job;<br />

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

alert(this.name);<br />

};<br />

}<br />

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

var person2 = new Person(“Greg”, 27, “Doctor”);<br />

152

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

Saved successfully!

Ooh no, something went wrong!