18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

Modifying Objects<br />

Creating your own objects is just part of the fun in ECMAScript. How would you like to modify the<br />

behavior of existing objects? This is completely possible in ECMAScript, so dream up whatever methods<br />

you’d like for a String, Array, Number, or any other object, because the possibilities are endless.<br />

Remember the prototype object from an earlier section in this chapter? You already know that each<br />

constructor has a prototype property that can be used to define methods. What you don’t already<br />

know is that each of the native objects in ECMAScript also has a prototype property that can be used<br />

in the exactly same way.<br />

Creating a new method<br />

You can define a new method for any existing class by using its prototype property, just as you would<br />

with your own classes. <strong>For</strong> instance, remember the toString() method of Number that outputs a hexadecimal<br />

string if you pass in 16 as an argument? Wouldn’t it be nicer to have a toHexString() method<br />

to handle the process? It’s simple to create it:<br />

Number.prototype.toHexString = function () {<br />

return this.toString(16);<br />

};<br />

Object Basics<br />

In this context, the this keyword points to the instance of Number and so has full access to all the<br />

Number methods. With this code, it is possible to do this:<br />

var iNum = 15;<br />

alert(iNum.toHexString());<br />

//outputs “F”<br />

Because the number 15 is equal to hexadecimal F, the alert displays “F”. And remember the discussion<br />

about using an Array as a queue? The only thing missing was properly named methods. You can add<br />

enqueue() and dequeue() to Array and just have them call the existing push() and shift() methods<br />

respectively:<br />

Array.prototype.enqueue = function(vItem) {<br />

this.push(vItem);<br />

};<br />

Array.prototype.dequeue = function() {<br />

return this.shift();<br />

};<br />

You can also, of course, add methods that don’t rely on existing methods at all. <strong>For</strong> example, say that<br />

you want to determine the position of a particular item in an array. You have no native method to do<br />

such a thing. You can easily create a method that does this:<br />

Array.prototype.indexOf = function (vItem) {<br />

for (var i=0; i < this.length; i++) {<br />

if (vItem == this[i]) {<br />

return i;<br />

99

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

Saved successfully!

Ooh no, something went wrong!