Heres a bit of cleaned up code from a picture gallery im writing to learn js.
I create the gallery as an object but at some point i lose track of what “this” points to.
It doesnt make sense to me what happens at the bottom (look at the comments).
Can someone please explain?
function Gallery(parentID)
{
// ...
this.showDiv = document.createElement("div");
// ...
this.show = function ()
{
document.body.appendChild(this.showDiv); //will be given css absolute position to "pop up"
this.showDiv.innerHTML = '<img class="displayImage" src="' + this.picList[this.showIndex] + '">'; //fill with image
this.showDiv.focus();
this.showDiv.onclick = this.hide;
}
this.hide = function ()
{
alert(this.innerHTML); // <= WHY DOES THIS SHOW THE INNERHTML CONTENTS OF this.showDiv??????
//alert(this.showDiv.innerHTML); // <= shouldnt this be correct?
this.parentNode.removeChild(this); //doesnt work
}
}
Let me know if i cleaned up some code that might have affected the results and ill fill it in.
Thanks.
This line is the problem. It doesn’t work like in Python;
this.hideis not a bound method. It’s just thehidefunction, not bound to any particularthis.One way to fix it is:
But the
.bind()method of functions is a rather new standard; it isn’t in all old browsers. So you might want to roll your own instead:(Generally
thisis kind of strangely behaved in JavaScript; the main thing to remember is thatthisalways refers to the innermost function’sthis, which could be whatever the caller wants it to be. Sometimes you see JS code do things likevar self = this;to give a particular function’sthisa name that can be used in nested functions; in Python, of course, that is just sort of the way things work automatically.)