Saturday, July 17, 2010

JavaScript - apply invocation pattern part 2

In my last post I promised a real-world example of the apply invocation pattern. The truth is it was getting late, and I didn't feel like writing anymore. However, one of my coworkers called me out, most likely because he's a JavaScript ninja and wants to put me in my place. In an effort to deny him the satisfaction, I'll steal an example from people who are smarter than I.

If you use jQuery, you've probably used the each function at some point. The each function works something like this (what follows is a vast oversimplification, see here for the actual implementation):

jQuery.extend({
  each: function(array, callback) {
    for (var i = 0; i < array.length; i++) {
      var value = array[i];

      //Apply callback with "this" as the current value
      callback.apply(value, [i, value]);
    }
  }
});

Now we can use the each function like this:

var sentence = '';
var words = ['hello', ' ', 'world', '!'];
jQuery.each(words, function() {
  sentence += this;
});
//sentence == 'hello world!'

No comments:

Post a Comment