title: image rollover object - javascript
body: <p>The following is a simple bit of code that can be used to create image rollovers (taken from a tutorial that I'm going through).  The author says: under the attach event handlers part, the constructor creates the two event handlers here.  It's within these event handlers that the variable named "that" has to be used to refer to the Rollover object.  That's because the "this" keyword within the event handlers refers to the image object, not the Rollover object.</p>
  
  <p>My question is: I understand that <code>this.image</code> refers to the image object but wouldn't you want to just set <code>this.image.src</code> equal to <code>this.newImageURL</code>?  I guess I just don't understand why <code>that</code> is necessary.  And how is it that changing the src property of <code>that.image</code> ends up changing the src property of `this.image?'</p>
  
  <pre><code>var $ = function (id) { return document.getElementById(id); }
  
  var Rollover = function ( imageId, newImageURL ) {
      var that = this;
      this.newImageURL = newImageURL;
      this.image = $(imageId);
  
      // Validate node
      if ( ! this.image ) {
          throw new Error("Rollover: Image ID not found.");
      }
      if ( this.image.nodeType !== 1 || this.image.nodeName !== "IMG" ) {
          throw new Error("Rollover: Image ID is not an img tag.");
      }
  
      var newObj = that;
      // Copy original image url
      this.oldImageURL = this.image.src;
  
      // Attach event handlers
      this.image.onmouseover = function () {
          that.image.src = that.newImageURL;
      }
      this.image.onmouseout = function () {
          that.image.src = that.oldImageURL;
      }
  }
  </code></pre>