SEARCH
0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Prev | Current Page 125 | Next

Jonathan Snook, Aaron Gustafson, Stuart Langridge, and Dan Webb

"Accelerated DOM Scripting with Ajax, APIs, and Libraries"

arr = arr;
}
SpecialArray.prototype.map = function(func)
{
for(var i = 0; i < this.arr.length; i++)
{
this.arr[i] = func(this.arr[i]);
}
return this;
}
var obj = new SpecialArray( ['A','B','C'] );
obj.map( function(el){ return el.toLowerCase() } ); // returns ['a','b','c']
First, there is a special new object called SpecialArray that has an internal array and one
method called map(). The map() method takes a function and runs that function on each of the
elements within the array. In this case, it changes all the elements from uppercase to lowercase.
By keeping it agnostic like this, you can manipulate the elements in the array any way
you please by simply passing in a different function:
obj.map( function(el){ return el + '!' } ); // returns ['A!','B!','C!']
You can even work with arrays of different object types:
var obj = new SpecialArray( [1,2,3] );
obj.map( function(el){ return el * el } ); // returns [1,4,9]
CHAPTER 3 n OBJECT-ORIENTED PROGRAMMING 77
Chainable Methods
You??™ve seen plenty of examples that follow the object.method() approach to things. However,
it can become cumbersome to assign something to a variable only to have to manipulate the
object further. Instead, you can often keep your code looking cleaner and simpler by chaining
methods together. This is quite common when working with string methods like this example:
"I went to my store".toUpperCase().replace("MY", "YOUR");
// returns "I WENT TO YOUR STORE"
With each method returning a string, you can continue to manipulate that string by
adding on new methods.


Pages:
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
odżywki Amarantus Najlepsza gra via www ochrona środowiska pompa ciepła