var myPrimes = [2,3,5,7,11]; /* The function forEach does something for every member of an array. action is the name of the function passed as an argument It looks like action is a function that is passed each member of the array in turn. It also looks like because forEach is used within sum forEach can also have access to total, so total is changed each time that the add function is applied to the array member. The adding up function being passed is called an anonymous function (because it is defined straight off the bat with the function keyword rather than being given a name and the name then being passed I think?) */ function forEach(array, action){ for (var n = 0; n != array.length; n++) action(array[n]); } function sum(numbers){ var total = 0; forEach(numbers,function(num){ total += num; }); return total; //you forgot to put this in the first time and it returned undefined } document.write(sum(myPrimes)); /* This case just illustrates passing a function by name rather than passing as an anonymous function. Note that the outside function - multiply - is really using two inner functions. One function is forEach that is defined elsewhere and the other is the mult function that actually does the work of multiplying stuff up. Note also that the outside function - multiply - also contains a variable that are used by the mult function as well - i.e. total and multiply is passed as an argument the array that it works on, although all mult does with the array is pass it off to forEach. So in other words multiply is a big function box that gets passed some data from outside (myPrimes), creates its own little variable - total - and function - mult and then uses a function form outside - forEach. The difficult part to understand is that multiply borrows the forEach function from outside its world by passing it its own named function - mult - although forEach is set up so that it can accept functions being passed as arguments. I guess that this is the function composition that gets talked about. Remember that multiply still has to return something to the outside world - i.e. total after multiplication!! */ function multiply(numbers){ var total = 1; function mult(x){ total *= x; } forEach(myPrimes, mult) return total; //and you forgot this time as well!!! } document.write(multiply(myPrimes)); /* Quote from the textbook: "...what forEach does is take an algorithm, in this case 'going over an array' and abstract it. The 'gaps' in the algorithm, in this case what to do with each of the elements, are filled by functions which are passed to this abstracted algorithm function. forEach is function that acts on another function - a higher order function. */
Tuesday, December 31, 2013
Eloquent javascript - passing functions as arguments
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment