Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...

When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Eight Weeks of Prototype: Week 3, Prototype Data Types


Prototype automatically extends the array type to give all of the functionality of enumerables. That is, you can you use methods such as each() on any array that you create.

Revisiting Listing 3 (which created a CSS colour string from 3 different variables), we can define the colours as an array then use the invoke() method (covered above) to create the string.

Listing 6 shows an example of doing so. When we call invoke with toColorPart() as the function to execute, an array is returned with each element corresponding to the result for each element in the input array. We can then join this value to create a single string from the returned array.

Listing 6 Using arrays and invoke to create hex colour codes (listing-6.html)
        <title>Using arrays and invoke to create hex colour codes</title>
        <script type="text/javascript" src="/js/prototype.js"></script>
        <div id="foo">
            This div will change colour!
        <script type="text/javascript">
            var colors = [ 255, 100, 0 ];
            var hexColors = colors.invoke('toColorPart');
            // same as [ 'ff', '64', '00' ]
            var hex = '#' + hexColors.join('');
            // hex will have the value #ff6400
            $('foo').setStyle({ backgroundColor : hex });
            // or this can be shortened further to:
            var hex = '#' + colors.invoke('toColorPart').join('');

In This Article