透過「拖曳效果」這個經典案例,示範如何將面向過程代碼逐步重構為面向物件(OOP)風格,理解 this 指向、原型鏈、封裝與複用的實務技巧。
window.onload = function() {
var oBox = document.getElementById('box');
var disX = 0, disY = 0;
oBox.onmousedown = function(e) {
e = e || window.event;
disX = e.clientX - this.offsetLeft;
disY = e.clientY - this.offsetTop;
document.onmousemove = function(e) {
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; // 防止文字選取
};
};
缺點:全域變數污染、難以建立多個獨立拖曳元素、邏輯與資料耦合。
// 建構函數
function Drag(id) {
this.obj = document.getElementById(id);
this.disX = 0;
this.disY = 0;
}
// 原型方法
Drag.prototype.init = function() {
var me = this; // 保存 this 參考
this.obj.onmousedown = function(e) {
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) {
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;
};
// 啟動
window.onload = function() {
new Drag('box').init();
new Drag('box2').init(); // 秒建立第二個拖曳元素
};
| 面向過程 | 面向物件 | 優勢 |
|---|---|---|
| 全域變數 disX/disY | 實例屬性 this.disX | 多實例互不干擾 |
| 巢狀函數 | 原型方法 | 方法共享、記憶體節省 |
| this 指向混亂 | var me = this 固定參考 | 回呼函數中正確存取實例 |
| 事件綁定在 onload | 封裝在 init() | 初始化時機可控、易測試 |
class Drag {
constructor(id) {
this.obj = document.getElementById(id);
this.disX = 0;
this.disY = 0;
this.boundMouseMove = this.mouseMove.bind(this);
this.boundMouseUp = this.mouseUp.bind(this);
}
init() {
this.obj.addEventListener('mousedown', this.mouseDown.bind(this));
}
mouseDown(e) {
this.disX = e.clientX - this.obj.offsetLeft;
this.disY = e.clientY - this.obj.offsetTop;
document.addEventListener('mousemove', this.boundMouseMove);
document.addEventListener('mouseup', this.boundMouseUp);
}
mouseMove(e) {
this.obj.style.left = (e.clientX - this.disX) + 'px';
this.obj.style.top = (e.clientY - this.disY) + 'px';
}
mouseUp() {
document.removeEventListener('mousemove', this.boundMouseMove);
document.removeEventListener('mouseup', this.boundMouseUp);
}
}
// 使用
new Drag('box').init();
new Drag('box2').init();
mouseMove 中加入 Math.max(0, Math.min(maxX, ...)) 限制拖曳範圍。touchstart/move/end,讀取 e.touches[0].clientX。CustomEvent 派發 dragstart/drag/dragend,供外部訂閱。從面向過程到面向物件,核心在於「將資料與操作資料的行為封裝在一起」。拖曳案例完美展示了 this 綁定、原型共享、多實例隔離等 OOP 精髓,是前端進階必練題目。