DIV CSS 佈局教程網

透過實現拖拽效果理解 JavaScript 面向對象
編輯:JavaScript綜合知識     

拖拽是前端非常經典的練習題,而它同時也是理解 JavaScript 面向對象編程的絕佳切入點。本文將帶大家先把拖拽用面向過程的思維寫出來,再逐步重構為面向對象的版本,從中體會兩種思路的差異與 this 指針的處理技巧。

面向對象重構的基本規則

在動手之前,先明確改造的規則:

· 盡量不要出現函數嵌套函數;
· 可以有全局變量;
· 把 onload 函數中不是賦值的語句放到單獨函數中。

改成面向對象時:

· 全局變量就是屬性;
· 函數就是方法;
· onload 中創建對象;
· 注意改 this 指針問題。

第一步:面向過程的拖拽

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;
};
};

第二步:重構為面向對象

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(){
var me = this; // 保存 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;
};

關鍵差異與注意事項

對比可見,重構後先用構造函數 Drag 創建對象,把原來的全局變量(如 obj、disX、disY)變成對象的屬性,把各段邏輯職能拆分成 init、mouseDown、mouseMove、mouseUp 等原型方法。最需要留意的是 this 指針問題:由於事件處理函數中的 this 會指向觸發事件的元素而非 Drag 實例,所以我們用 var me = this 把真正的 this 保存下來,再在內部方法中透過 me 調用。此外,由於 event 對象只存在於事件中,我們還需要把它作為參數顯式傳遞。掌握這些技巧,就能寫出結構清晰、易於維護的面向對象拖拽代碼了。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved