Actually, the book is incorrect there. I don't know what I was
thinking. The function in the example is anonymous, and therefore
bound to the window. I'm a moron. It's fixed in the next edition.
-Aaron
Sorry for any typos. Big fingers , tiny buttons.
On Aug 13, 2009, at 1:48 PM, nwhite <[email protected]> wrote:
The quick solution
['blue','green','yellow'].each(function(value, index,arr){
alert('item ' + index + ' is ' + value);
if (index ==arr.length-1) arr[index] = 'orange';
//Changes the last item in the array to 'orange'
});
each has a third parameter that it passes to your anonymous
function. The book is correct in its explanation of 'this' however
you are inside an anonymous function, so 'this' refers to the
function. This explains why each has the 3rd parameter.
Your code is not really ideal since all you do is change the last
item in the array to 'orange', but you loop through each item to
accomplish this.
An alternative approach using the 'this' syntax on an array.
Array.implement({
changeLast : function(val){
this[this.length-1] = val;
return this;
}
});
your above code would change to this
['blue','green','yellow'].changeLast('orange');
On Thu, Aug 13, 2009 at 1:33 PM, rabidPraxis
<[email protected]> wrote:
I am having an issue with the way binding is explained in the appendix
of MooTools Essentials. It states that the 'this' in the function
below should reference the Array instance that is calling it (in this
case an anonymous array). When I run an example like this (MooTools
1.2.3, Firefox 3.5.1), 'this' is always referenced to Window.
['blue','green','yellow'].each(function(value, index){
alert('item ' + index + ' is ' + value);
if (index == this.length-1) this[index] = 'orange';
//Changes the last item in the array to 'orange'
});
Am I missing something here?