雖然 JS 可以像物件導向那樣建構物件、隱藏私有方法,但需求變動往往比你寫程式還快,常常連設計 JS 物件的時間都沒有,所以我比較傾向直接用 JS 私有函式搭配對外方法。jQuery 的私有函式加對外方法也能達到同樣效果。
頁面產生的 HTML 結構完全在 JS 中生成,包含 id 與 class,這樣可以最大程度確保統一與重用的方便性。缺點是重用時若需要調整樣式(結構是固定的,不能變),就得用一個 div 把原本的結構包起來,相關樣式也要用對應的 id 再包一層;如果是新增事件,則只能用綁定的方式,目前還沒有更好的解法。
例如我要實作在一個 div 中包含幾張圖片。這樣做也有個缺點:CSS 必須複製一份再修改,但結構、樣式與 JS 都能重用。
. 程式碼如下:
<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
var publicSetDiv = function (url, id) {
// 作為對外公開的,可以傳參進行
this.makediv = function (j) {
var imglist = makeimglist(url, j);
$(id).html(imglist);
$(id).show();
}
// 私有的
function makeimglist(url, j) {
var i = 0;
//var j = 10;
var html = "";
for (i; i < j; i++) {
html += "<img src='" + url + "' class='item' />";
}
return html;
}
}
$(document).ready(function () {
// Handler for .ready() called.
var mytest = new publicSetDiv("https://images.cnblogs.com/logo_small.gif", "#test");
mytest.makediv(10);
var mytest2 = new publicSetDiv("https://images.cnblogs.com/logo_small.gif", "#test2");
mytest2.makediv(10);
});
</script>
<%-- 原始預設的樣式--%>
<style type="text/css">
.item{ width:200px; height:100px; }
#test2 .item{ width:200px; height:100px; }
</style>
<%-- 第二次使用該樣式並稍作修改 --%>
<style type="text/css">
#test2 .item{ width:200px; height:200px; background-color:Black; }
</style>
</head>
<body>
<form id="form1" runat="server">
第一次使用
<div id="test" style=" display:none;">
</div>
<div id="test2" style=" display:none;">
</div>
</form>
</body>
</html>
核心手法是:makeimglist 藏在閉包裡不對外暴露,只把 makediv 掛成公開方法;而樣式覆寫則靠 #test2 .item 這種後代選取器,讓同一份結構在不同容器裡長出不同模樣。