Javascript this as a parameter

This is not this object!

Javascript is really unexpected in term of object orientation, particularly for me that I come from a Java background. The least expected surprised I got from the object reference this. Consider the following jQuery each example:

list = $("ul");
[  <ul id=​"letters">​ <li>​A​</li> <li>​B​</li>​     <li>​C​</li>​     </ul>​ ];
$("li").each(function(){ console.log( $(this).text() ) });
A
B
C
This happens thanks to jQuery, binding the this object to the item over which it iterates. For instance, if we use Underscore, we would have a different result, but a more expected one in Javascript:
_.each( $("li"), function(a){ console.log( this ) } )
(3) DOMWindow
This happens because underscore binds the this reference to DOMWindow, the ‘owner’ of the context where it is executing. At first glance appears to be a problem but in fact turns out to be very useful, for instance to reference the list:
   _.each( $("li"), function(a){ 
      console.log( $(a).text() + " in list " + l.attr('id') ) 
   }, list )
A in list letters
B in list letters
C in list letters

Wow! It is a nice type of magic, allowed by the ugly function apply that tells the lambda function to be applied to all arguments with a specific owner object this.

Leave a Reply