iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 26
0
自我挑戰組

前端我來了 - 30天 JavaScript 從無到有 系列 第 26

[30天 JavaScript 從無到有 Day 26] Module Pattern

  • 分享至 

  • twitterImage
  •  

模組模式 (Module Pattern)

透過函式的 closure 特性 : 封裝函式和變數
透過 IIFEs 特性 : 立刻呼叫
JavaScript 沒有 public、private概念 : 透過程式結構實踐

-> 透過 closure,將變數、函式限制於一個範圍,限制其存取、使用

好處:將函式、變數模組、私有化,避免混雜於全域中,也能隱藏實作。

Sample-1 by IIFEs

var testController = (function() {
    
    var n = 23;
    
    var add = function(x){
        return n + x;
    }
    
    return {
        publicTest: function(a) {
            console.log(add(a))
        }
    }
})()

依據 IIFEs 特性,testController 在執行時會被立即呼叫

  • n -> private (存於函式內)
  • add -> private (存於函式內)
  • publicTest -> public (回傳值)
test at the console

input : budgetController.x
output : undefined

input : budgetController.add(5)
output : undefined

input : budgetController.publicTest(5)
output : 28

Sample-2 by multiple IIFEs

var testController = (function() {
    
    var n = 23;
    
    var add = function(x){
        return n + x;
    }
    
    return {
        publicTest: function(a) {
            return add(a);
        }
    }
})()

var UIController = (function() {
    
    // unused now
    
})()


var controller = (function(testCtrl, UICtrl){
    
    var b = testCtrl.publicTest(5);
    return {
        secPublic: function() {
            console.log(b);
        }
    }
})(testController, UIController)

將 publicTest() 原本的console.log 改為 return 值,透過 controller 跨函式進行存取

test at the console

input : controller.secPublic()
output : 28

b 來自於 testCtrl.publicTest(),透過 closure 概念,函式能存取的範圍包含其內含以及往外推,
controller.secPublic() -> controller(testCtrl, UICtrl) -> testController


課程 : https://www.udemy.com/course/the-complete-javascript-course/
來源 :
http://cythilya.blogspot.com/2015/06/javascript-module-pattern.html
https://ithelp.ithome.com.tw/articles/10215129


上一篇
[30天 JavaScript 從無到有 Day 25] Closure & call / apply / bind
下一篇
[30天 JavaScript 從無到有 Day 27] 實作筆記-1
系列文
前端我來了 - 30天 JavaScript 從無到有 30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言