prototype.getNext = function()
{
return this.items[++this.current];
}
Collection.prototype.getPrevious = function()
{
return this.items[--this.current];
}
var coll = new Collection( [1,2,3,4] );
alert( coll.getCurrent() ); // 1
alert( coll.getNext() ); // on to 2
alert( coll.getPrevious() ); // back to 1
You have your main Collection class, which stores a pointer to the current item and the
array in a property called items. The getCurrent(), getNext(), and getPrevious() methods
enable you to move back and forth within the array, constantly updating the current pointer.
It could be extended with the map() function you saw earlier, along with error detection to
check whether you have reached the end or beginning of the collection.
Many of the JavaScript libraries have implemented iterators and offer plenty of methods
that can be extremely handy in working with collections of data like this.
Summary
In this chapter, you got a good sense of some object-oriented programming using JavaScript.
Some of the things you should know before you move on include the following:
??? The different ways to create objects and when it is beneficial to use one instead of
another
??? How to extend objects with methods and properties and when to use the prototype
property
??? How to take advantage of closures
??? How to use callbacks
Chapter 4 dives into the wonderful world of JavaScript libraries to learn what they have to
offer, and why and how you should use them.
Pages:
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139