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.
My question is: I understand that this.image
refers to the image object but wouldn't you want to just set this.image.src
equal to this.newImageURL
? I guess I just don't understand why that
is necessary. And how is it that changing the src property of that.image
ends up changing the src property of `this.image?'
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;
}
}
In javascript the this variable changes with scope. The first line of var that = this;
this refers to the Rollover object. Setting that = this basically just creates a pointer to Rollover.
In any subsequent event call like
this.image.onmouseover = function () {
that.image.src = that.newImageURL;
}
In the function callback this now refers to the event scope - this now points to the object that was rolled over. Thats why this.image wouldn't point to anything because the DOM element being moused over does not have an image property. Because you already set another variable (that) to the Rollover instance (original this), you can now use it in any of the other scopes.