When I run this sample code in Google Chrome, the intended behavior–loading an image within a placeholder image tag on the current page–does not occur. I checked the value of currPic when showPic() is called, and it is “undefined.” I know if I change the parameter to showPic from ‘anchors[i]’ to ‘this’, then it will work, but was trying to understand why this is so.
function showPic(currPic) {
var srcLoc = currPic.getAttribute("href");
var placeHolder = document.getElementById("placeholder");
placeHolder.setAttribute("src", srcLoc);
var imgLabel = document.getElementById("imglabel");
var currLinkTitle = currPic.getAttribute("title");
imgLabel.firstChild.nodeValue = currLinkTitle;
}
function prepareGallery() {
if(!(document.getElementsByTagName && document.getElementById)) return false;
var imgGallery = document.getElementById("imagegallery");
if(imgGallery) {
var anchors = imgGallery.getElementsByTagName("a");
var i;
for(i = 0; i < anchors.length; i++) {
anchors[i].onclick = function() {
showPic(anchors[i]);
return false;
}
}
}
}
Inside the anonymous function, anchors[i] provides a runtime reference. At the time the click occurs,
anchors[i]no longer exists. While it existed at the time the assignment was made, it falls out of scope at the time of the click (since it’s just an array reference). However, usingthisprovides a solid reference to the immediate object that is always available at the time of the click.More succinctly,
anchors[i]is a reference to a position in an array (which leaves scope once the for loop exits).thisis a reference to the dom element itself.