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 124 | Next

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

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


Here??™s an example that demonstrates the relationship between everything:
function ObjectA(){ /* stuff */ }
ObjectA.methodB = function ()
{
// arguments now has 6 elements:
alert($A(arguments)); // 1,2,3,4,5,6
}
var bound = ObjectA.methodB.bind(ObjectA, '1','2','3','4');
bound('5','6');
CHAPTER 3 n OBJECT-ORIENTED PROGRAMMING 76
Using call or apply, especially as shown here, can make your code look cleaner and more
readable.
Applying a Function to a Collection
A handy way to use callbacks is to apply a function to a series of elements within an array or
object (which are very similar in functionality). The ability to receive functions as parameters
enables you to apply a function to any and all items within a collection.
Here??™s a great example taken from jQuery (http://jquery.com):
$("p").each(function(){
this.innerHTML = this + " is the Element";
});
Despite the brevity of this code example, there??™s actually a lot happening here. First, a
function called $() takes in a string parameter. In this case, it finds all

elements on the
page. In other words, $("p") returns a collection of paragraphs in the document. Then, the
each() method will apply a function to each item in the collection (in this case, the innerHTML
of each paragraph tag will be replaced with the string).
You can create your own example now that will parse through your own special array:
function SpecialArray(arr)
{
this.


Pages:
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136