If you begin chaining a lot of methods, you can make the code
cleaner by putting each subsequent call onto its own line:
"I went to my store"
.toUpperCase()
.replace("MY", "YOUR");
// returns "I WENT TO YOUR STORE"
To create your own chainable methods, you simply have to ensure that you are always
returning something at the end of a method call. With that returned data, you can continue to
manipulate it.
Using the SpecialArray, you can continue to manipulate the array with subsequent map
calls because you return the SpecialArray on which you??™re performing the map:
var obj = new SpecialArray( ['A','B','C'] );
var arr = obj
.map( function(el){ return el.toLowerCase() } ) // returns ['a','b','c']
.map( function(el){ return el += '!' } ); // returns ['a!','b!','c!']
Internal Iterators
Collections are quite common in DOM scripting??”from a simple array to a node list returned
from a getElementsByTagName() call. Creating a class??”or extending the ones built into
JavaScript??”can give you added flexibility to be able to manipulate those collections. An
internal iterator is a mechanism that enables you to navigate through a collection using
exposed elements.
Here??™s an example collection object that enables you to navigate:
function Collection (arr)
{
this.current = 0;
this.items = arr;
}
Collection.prototype.getCurrent = function()
{
return this.items[this.current];
}
CHAPTER 3 n OBJECT-ORIENTED PROGRAMMING 78
Collection.
Pages:
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138