以下は、画像のロールオーバーを作成するのに使用できる簡単なコードです(チュートリアルから抜粋します)。著者は言う:attachイベントハンドラ部分の下で、コンストラクタはここに2つのイベントハンドラを作成します。これらのイベントハンドラ内には、ロールオーバーオブジェクトを参照するために "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'が使用されています。 –