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

Alternate Prototype Syntax<br />

You may have noticed in the previous example that Person.prototype had to be typed out for each<br />

property and method. To limit this redundancy and to better visually encapsulate functionality on the<br />

prototype, it has become more common to simply overwrite the prototype with an object literal that<br />

contains all of the properties and methods, as in this example:<br />

function Person(){<br />

}<br />

Person.prototype = {<br />

name : “Nicholas”,<br />

age : 29,<br />

job : “Software Engineer”,<br />

sayName : function () {<br />

alert(this.name);<br />

}<br />

};<br />

In this rewritten example, the Person.prototype property is set equal to a new object created with an<br />

object literal. The end result is the same, with one exception: the constructor property no longer points<br />

to Person . When a function is created, its prototype object is created and the constructor is<br />

automatically assigned. Essentially, this syntax overwrites the default prototype object completely,<br />

meaning that the constructor property is equal to that of a completely new object (the Object<br />

constructor) instead of the function itself. Although the instanceof operator still works reliably, you<br />

cannot rely on the constructor to indicate the type of object, as this example shows:<br />

var person = new Person();<br />

alert(person instanceof Object); //true<br />

alert(person instanceof Person); //true<br />

alert(person.constructor == Person); //false<br />

alert(person.constructor == Object); //true<br />

Here, instanceof still returns true for both Object and Person, but the constructor property is<br />

now equal to Object instead of Person . If the constructor ’ s value is important, you can set it<br />

specifically back to the appropriate value as shown here:<br />

function Person(){<br />

}<br />

Person.prototype = {<br />

constructor: Person,<br />

name : “Nicholas”,<br />

age : 29,<br />

job : “Software Engineer”,<br />

sayName : function () {<br />

alert(this.name);<br />

}<br />

};<br />

This code specifically includes a constructor property and sets it equal to Person , ensuring that the<br />

property contains the appropriate value.<br />

162

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

Saved successfully!

Ooh no, something went wrong!