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.

function Robot(flying, action)<br />

{<br />

}<br />

if (flying == true)<br />

this.hasJetpack = true;<br />

if (action)<br />

this.actionValue = action;<br />

We have added a new property to the prototype, actionValue. This property has a default value<br />

that can be overridden by passing a second argument to the constructor. If a value for action is<br />

passed to the constructor, invoking doAction() will show its value rather than the default<br />

("Intruders beware!"). For example,<br />

var guard = new Robot(true, "ZAP!");<br />

guard.doAction();<br />

results in ―ZAP!‖ being alerted rather than ―Intruders beware.‖<br />

Dynamic Types<br />

A very important aspect of the prototype is that it is shared. That is, there is only one copy of<br />

the prototype that all objects created with the same constructor use. An implication of this is<br />

that a change in the prototype will be visible to all objects that share it! This is why default<br />

values in the prototype are overridden by instance variables, and not changed directly.<br />

Changing them in the prototype would change the value for all objects sharing that prototype.<br />

Modifying the prototypes of built-in objects can be very useful. Suppose you need to repeatedly<br />

extract the third character of strings. You can modify the prototype of the String object so that<br />

all strings have a method of your definition:<br />

String.prototype.getThirdChar = function()<br />

{<br />

}<br />

return this.charAt(2);<br />

You can invoke this method as you would any other built-in String method:<br />

var c = "Example".getThirdChar(); // c set to 'a'<br />

Class Properties

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

Saved successfully!

Ooh no, something went wrong!