11.12.2012 Views

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

}<br />

this.hasJetpack = true;<br />

This example adds an instance property hasJetpack to each new object it creates. After<br />

creating an object with this constructor, we can access the hasJetpack property as one would<br />

expect:<br />

var guard = new Robot();<br />

var canFly = guard.hasJetpack;<br />

Since constructors are functions, you can pass arguments to constructors to specify initial<br />

values. We can modify our constructor again so that it takes an optional argument:<br />

function Robot(needsToFly)<br />

{<br />

}<br />

if (needsToFly == true)<br />

else<br />

this.hasJetpack = true;<br />

this.hasJetpack = false;<br />

// create a Robot with hasJetpack == true<br />

var guard = new Robot(true);<br />

// create a Robot with hasJetpack == false<br />

var sidekick = new Robot();<br />

Note that in this example we could have explicitly passed in a false value when creating the<br />

sidekick instance. However, by passing in nothing, we implicitly have done so, since the<br />

parameter needsToFly would be undefined. Thus, the if statement fails properly.<br />

We can also add methods to the objects we create. One way to do so is to assign an instance<br />

variable an anonymous function inside of the constructor, just as we added an instance<br />

property. However, this is a waste of memory because each object created would have its own<br />

copy of the function. A better way to do this is to use the object‘s prototype.<br />

Prototypes<br />

Every object has a prototype property that gives it its structure. <strong>The</strong> prototype is a reference to<br />

an Object describing the code and data that all objects of that type have in common. We can

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

Saved successfully!

Ooh no, something went wrong!