章節連結
JavaScript 的 Class 與工廠函式都可用於封裝狀態、事件、隱藏內部使用的變數,讓後續管理上變得容易。這邊筆記下兩著寫法的區別和 Demo。
內容
比較表
項目 | Class | Functional programming ( FP ) |
---|---|---|
擴展性 | 高,適合添加更多功能與繼承 | 低,功能擴充需修改原函式 |
效能 | 稍大( 需建立 class Instance ) | 輕量,適合簡單用途 |
狀態管理 | 內建透過 this 管理屬性與狀態 |
使用閉包 Closure 維持狀態 |
事件綁定 | 事件集中在 constructor 裡 | 綁定較分散,增加維護成本 |
相依風格 | 接近大型前端框架寫法( 如 Vue/React Class API ) | 傾向 jQuery 寫法 |
程式碼 Demo
FP Version
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
/** * Rely on jQuery & Bootstrap 3.3.7 */ const useTriggerModal = (targetDomStr) => { const targetDom = $(targetDomStr); const modalBody = targetDom.find('.modal-body'); const bodyDom = document.querySelector('body'); const fixedDomOverflow = (dom, boolean) => { if (!dom) return dom.style.overflow = boolean ? 'hidden' : '' } if (!targetDom) { console.error(Target Dom Element not found: ${targetDomStr}); return {}; } const addContent = (content) => { if(modalBody){ modalBody.html(content); } } const showModal = (triggerEl) => { const content = $(triggerEl).data('content') if(targetDom){ addContent(content); fixedDomOverflow(bodyDom, true) targetDom.modal('show') } } const clearContent = () => { if(modalBody){ modalBody.html(''); } } targetDom.on('hide.bs.modal', function () { clearContent() fixedDomOverflow(bodyDom, false) }) return { addContent, clearContent, showModal, } } |
Class Version
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
/** * Rely on jQuery & Bootstrap 3.3.7 */ class TriggerModal { constructor(targetDomStr) { this.targetDom = $(targetDomStr); this.modalBody = this.targetDom.find('.modal-body'); this.bodyDom = document.querySelector('body'); if (!this.targetDom.length) { console.error(`Target Dom Element not found: ${targetDomStr}`); return; } this.targetDom.on('hide.bs.modal', () => { this.clearContent(); this.fixedDomOverflow(false); }); } fixedDomOverflow(enable) { if (!this.bodyDom) return; this.bodyDom.style.overflow = enable ? 'hidden' : ''; } addContent(content) { if (this.modalBody) { this.modalBody.html(content); } } clearContent() { if (this.modalBody) { this.modalBody.html(''); } } showModal(triggerEl) { const content = $(triggerEl).data('content'); if (this.targetDom.length) { this.addContent(content); this.fixedDomOverflow(true); this.targetDom.modal('show'); } } } |
參考資料
1. Day37 Prototype 工廠函式 v.s. 建構子函式
按讚加入粉絲團