同一個拖曳功能,用面向過程寫一次,再重構為物件導向寫一次,是理解 this 指標與原型繼承最有效的方式。本文就把這個改造過程完整走一遍。
動手之前先訂好幾條原則,重構時才不會越改越亂:
改成物件導向時,對應的轉換規則是:全域變數變成屬性,函式變成方法,onload 裡只負責建立物件,並妥善處理 this 指標的指向問題。
<div id="box"></div>
#box { position: absolute; width: 200px; height: 200px; background: red; }
window.onload = function () {
// 取得元素與初始值
var oBox = document.getElementById('box'),
disX = 0, disY = 0;
oBox.onmousedown = function (e) {
var e = e || window.event;
disX = e.clientX - this.offsetLeft;
disY = e.clientY - this.offsetTop;
document.onmousemove = function (e) {
var e = e || window.event;
oBox.style.left = (e.clientX - disX) + 'px';
oBox.style.top = (e.clientY - disY) + 'px';
};
document.onmouseup = function () {
document.onmousemove = null;
document.onmouseup = null;
};
return false;
};
};
用構造函式把元素與偏移量收進屬性,各個行為掛到原型上,onload 只剩建立與啟動:
window.onload = function () {
var drag = new Drag('box');
drag.init();
};
// 構造函式
function Drag(id) {
this.obj = document.getElementById(id);
this.disX = 0;
this.disY = 0;
}
Drag.prototype.init = function () {
// 用 me 保存 this,避免後續指標跑掉
var me = this;
this.obj.onmousedown = function (e) {
var e = e || event;
me.mouseDown(e);
return false; // 阻止預設行為
};
};
Drag.prototype.mouseDown = function (e) {
var me = this;
this.disX = e.clientX - this.obj.offsetLeft;
this.disY = e.clientY - this.obj.offsetTop;
document.onmousemove = function (e) {
var e = e || window.event;
me.mouseMove(e);
};
document.onmouseup = function () {
me.mouseUp();
};
};
Drag.prototype.mouseMove = function (e) {
this.obj.style.left = (e.clientX - this.disX) + 'px';
this.obj.style.top = (e.clientY - this.disY) + 'px';
};
Drag.prototype.mouseUp = function () {
document.onmousemove = null;
document.onmouseup = null;
};
第一是 this 指標。事件處理函式被呼叫時,其中的 this 會指向觸發事件的元素,而不是 Drag 實例。因此在 init 與 mouseDown 開頭先用 var me = this 把正確的參照存下來,後續在事件回呼中一律透過 me 存取,指標才不會錯位。
第二是 event 物件。event 只在事件處理的當下有效,一旦離開該函式就取不到,所以必須先存成變數、再以參數形式傳給 mouseDown 等方法。這也是為什麼 mouseDown 要明確宣告 e 參數。
把這兩個觀念吃透,之後寫任何需要跨事件傳遞狀態的元件(例如縮放、畫布操作),都能少走很多彎路。