I want to create the following JavaScript object:
function Thumbnail(thumbnailUrl) {
this.thumbnailUrl = thumbnailUrl;
this.width = 200;
this.height = 150;
this.element = init(this.width, this.height, this.thumbnailUrl);
this.element.addEventListener("mouseover",this.onmouseover);
function init(width, height, thumbnailUrl) {
var thumbViewHTML = "<div class='container shadow' style='width:"+width+"px; height:"+height+"px; background: green;'>";
thumbViewHTML += "<div class='container' style='width:100%; height:80%; background: yellow'>";
thumbViewHTML += "<img class='centered' src='"+thumbnailUrl+"' style = 'max-width: 100%; max-height: 100%;'/>";
thumbViewHTML += "</div>";
thumbViewHTML += "<div class='container' style='width: 100%; height:20%; background: black'>";
thumbViewHTML += "<div class='textStyle centeredVertically' style='margin-left:5px; color: white'>Landscape</div>";
thumbViewHTML += "</div>";
thumbViewHTML += "</div>";
return DOMElementFromHtml(thumbViewHTML);
}
return this;
}
Thumbnail.prototype.onmouseover = function() {
console.log(this.width); //undefined with this pointing to this.element property on the Thumbnail object
}
function DOMElementFromHtml(htmlString) {
var tempDiv = document.createElement('div');
tempDiv.innerHTML = htmlString;
return tempDiv.firstChild;
}
When I access this.width
on the onmouseover
handler I get undefined because this points to the this.element
member of the Thumbnail
object. Is there any way to get this
inside that method to point to the Thumbnail
instance instead of the this.element
instance.
I assume I could implement onmouseover
in the local scope of the Thumbnail
constructor and that might work but what if I want onmouseover
to be a public method that can be modified externally?