我想創建以下JavaScript對象:如何通過下面的示例正確訪問javascript對象屬性?
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;
}
當我在onmouseover
處理程序訪問this.width
我得到未定義因爲這指向Thumbnail
對象的this.element
成員。有沒有辦法在該方法內獲得this
指向Thumbnail
實例而不是this.element
實例。
我認爲我可以在Thumbnail
構造函數的局部範圍內實施onmouseover
和可能的工作,但如果我想onmouseover
是可以向外進行修改的公共方法是什麼?
我真的很陌生,對我來說這麼裸露的JavaScript。
主題你叫'''新的縮略圖()'''? –