# 1.6.Module

* 模組化的好處
* 模組
  * 當要為相同介面產生多個實作時, 可撰寫一個預設實作作為原型, 可使用stampit(<https://github.com/stampit-org/stampit>)
  * stampit: a coposable factory
    * API doc:<https://github.com/stampit-org/stampit/blob/master/docs/API.md#stamppropsargs-and-stamppropertiesargs>
    * stampit.init
      * 初始化property, 可傳入參數
      * example:

        ```
        // Allow dbConnection to be passed from outside.
         const AcceptsDbConnection = stampit()
         .init(function ({dbConnection}) {
            this.dbConnection = dbConnection;
          });
        ```
    * stampit.props
      * 當初始化完成後指定進行後續動作,或是可以賦值給property\
        \*example:

        ```
        // Assigns the default connection string.
        const DefaultConnectionConfig = stampit()
        .init(function ({connectionConfig}) { // can pass the string as factory argument
          this.connectionConfig = connectionConfig;
         })
        .props({ // if nothing was passed this value will be used
          connectionConfig: require('./config.json').db.connection
        });
        ```
    * stampit.methods
      * 定義function
      * example:

        ```
        // Adds .log() method to factory instantiated objects.
        const Logger = stampit()
          .methods({
            log: console.log
          });
        ```
    * stampit.compose
      * 允許繼承任意數量的來源 (with last-in priority.)
      * example:

        ```
        // The connection object.
        const DbConnection = stampit()
        .props({ // Assigns the mongoose connection object.
          dbConnection: mongoose.connection
        })
        .compose(
          Logger, // add logging capability via this.log() 
          DefaultConnectionConfig, // add the default this.connectionConfig value
          AcceptsDbConnection // allow passing dbConnection as argument
        )
        .init(function () { // Connecting to the DB upon creating an object.
          if (!this.dbConnection.readyState) {
            this.dbConnection.open(this.connectionConfig);
            this.log('Opening a DB connection');
          }
        })
        .methods({ // A method to close the connection.
          close() {
            if (this.dbConnection.readyState) {
              this.dbConnection.close();
              this.log('Closing the DB connection');
            }
          }
        });
        ```
* 常見的模組
  * 模組模式 (module pattern)
  * 非同步模組定義 (AMD)
    * AMD模組載入器
      * Require.js
      * Curl.js
  * CommonJS模組規範
    * 是一個由CommonJS group所定出的module format, 是在Node上使用的模組撰寫風格
    * webpack 也是遵循這個規範
    * 匯出: export
    * 匯入: require
  *
