一、為什麼用構造函數模式
1. 業務邏輯的脈絡更清楚;
2. 避免製造大量全域變數——只留下一個全域變數,相當於這個功能模組對外唯一的入口;
3. 若搭配模組化開發,自訂模組很容易收攏進統一的 modules 裡,只要名稱不衝突就不會互相干擾;
4. 可維護性高,利人利己。
二、以拖拽為例
1. HTML 結構
<body> <div class="box" id="box1"><div class="main"><div class="bar">拖拽區</div><div class="content">內容區塊</div></div></div> <div class="box" id="box2"><div class="main"><div class="bar">拖拽區</div><div class="content">內容區塊</div></div></div> <div class="box" id="box3"><div class="main"><div class="bar">拖拽區</div><div class="content">內容區塊</div></div></div> </body>
2. CSS
.box{position:absolute;left:100px;top:100px;padding:5px;box-shadow:2px 2px 4px #666666;font-size:12px;}
#box2{left:500px;}
#box3{left:900px;}
.main{border:1px solid #a0b3d6;background-color:#fff;}
.bar{line-height:24px;padding-left:5px;border-bottom:1px solid #a0b3d6;background-color:#beceeb;cursor:move;}
.content{padding:10px 5px;height:200px;width:250px;}
3. JavaScript
// 定義 Drag 構造函數,設定每個實例的私有屬性
function Drag(bar, target) {
this.bar = bar; // 觸發拖拽的物件(標題列)
this.target = target; // 真正被拖動的物件
this.flag = false; // 開關,用來判斷拖拽是否進行中
}
Drag.prototype = {
constructor: Drag, // 重新指定 constructor,讓實例的來源明確
init: function () {
// this 指向呼叫 init 的實例;先存成 temp,後續在事件回呼中才不會指錯對象
var temp = this;
temp.left = temp.getCss(temp.target, "left"); // 初始 left
temp.top = temp.getCss(temp.target, "top"); // 初始 top
temp.mousePosX = null; // 滑鼠按下瞬間的位置
temp.mousePosY = null;
temp.bindEvent();
},
// 元素 style 屬性只能拿到行內樣式;外聯與內嵌樣式表得靠 currentStyle(IE)或 getComputedStyle
getCss: function (o, prop) {
return o.currentStyle ? o.currentStyle[prop]
: document.defaultView.getComputedStyle(o, null)[prop];
},
bindEvent: function () {
// 把實例存進 temp:事件回呼內部的 this 會指向觸發事件的元素,而不是我們的實例
var temp = this;
temp.bar.onmousedown = function (e) {
e = e || window.event; // 舊 IE 需從 window.event 取
temp.flag = true; // 按下即開啟開關
temp.mousePosX = e.clientX;
temp.mousePosY = e.clientY;
};
// 綁在 document 上,因為滑鼠是在整個文件範圍移動
document.addEventListener('mousemove', function (e) {
e = e || window.event;
if (temp.flag) {
// (e.clientX - temp.mousePosX) 是按下後滑動的距離,加上初始位置即為新座標
temp.target.style.left = parseInt(temp.left) + e.clientX - temp.mousePosX + "px";
temp.target.style.top = parseInt(temp.top) + e.clientY - temp.mousePosY + "px";
}
});
document.addEventListener('mouseup', function () {
temp.flag = false; // 關掉開關,停止拖動
temp.left = temp.getCss(temp.target, "left"); // 記錄放開後的位置
temp.top = temp.getCss(temp.target, "top");
});
}
};
var oBox = document.getElementsByClassName('box');
var oBar = document.getElementsByClassName('bar');
var drag1 = new Drag(oBar[0], oBox[0]);
var drag2 = new Drag(oBar[1], oBox[1]);
var drag3 = new Drag(oBar[2], oBox[2]);
drag1.init();
drag2.init();
drag3.init();
這裡最值得記住的是兩件事:用 temp 保存 this,避免事件回呼中的 this 指向被綁定的元素;以及 mousemove/mouseup 綁在 document 而非元素上,否則多個實例時只有最後初始化的那個能正常運作。