다음은 이미지 롤오버를 만드는 데 사용할 수있는 간단한 코드입니다 (자습서에서 가져옴). 작성자의 말 : 첨부 이벤트 핸들러 부분 아래의 생성자는 여기에 두 개의 이벤트 핸들러를 만듭니다. 이러한 이벤트 핸들러 내에서 "that"이라는 변수는 롤오버 객체를 참조하는 데 사용해야합니다. 이는 이벤트 처리기 내의 "this"키워드가 롤오버 객체가 아니라 이미지 객체를 참조하기 때문입니다.이미지 롤오버 객체 - javascript
내 질문은 : this.image
은 이미지 개체를 참조하지만 this.image.src
을 this.newImageURL
과 동일하게 설정한다는 것을 알고 있습니까? 나는 왜 that
이 필요한지 이해하지 못한다고 생각합니다. src 속성을 that.image
으로 변경하면 결국 'this.image?'의 src 속성이 변경됩니다.
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;
}
}
'this.image.onmouseover/out'에서'this'는'Rollover'에 의해 생성 된 객체가 아니라 image 요소를 참조하기 때문에'that'이 사용됩니다. –