LoginSignup
12
14

More than 1 year has passed since last update.

【JavaScript】モジュール化してみたい

Last updated at Posted at 2014-03-15

##JavaScriptでのモジュール化

モジュールを作成しておけば、その内部状態や実装について隠蔽した上で機能のみを提供できる。
JavaScriptでは関数を利用することで、モジュールを作成することが可能となる。

例)日付演算モジュール
var dateCalculator = function() {
  var year = 0,
      month = 0,
      day = 0;
  return {
    setYear: function(y) {
      year = y;
    },
    setMonth: function(m) {
      month = m;
    },
    setDay: function(d) {
      day = d;
    },
    // 表示
    printDate: function() {
      console.log(year + '' + month + '' + day + '');
    },
    // うるう年判定
    isLeapYear: function() {
      return ((year%4===0 && year%100!==0) || year%400===0);
    },
    // 月末日計算
    getLastDay: function() {
      var date = new Date(year, month, 0);
      return date.getDate();
    }
  };
};

var calc = dateCalculator();
calc.setYear(2014);
calc.setMonth(2);
calc.setDay(1);
calc.printDate(); // 出力:2014年2月1日
console.log(calc.isLeapYear()); // 出力:false
console.log(calc.getLastDay()); // 出力:28

// year, month, dayを直接参照することはできない
console.log(calc.year); // 出力:undefined
console.log(year); // エラー:year is not defined

dateCalculatorは、関数式の返却値としてセッターメソッドや日付演算を行うメソッド群をプロパティとしたオブジェクトを受け取っており、それらのプロパティへアクセスが可能である。
しかし、受け取ったオブジェクト内にはyear, month, dayといったプロパティは存在しないため、アクセスしてもundefinedと出力される。

##最後に...
日付関連の演算をする上で、以下のエントリが非常に参考になりました。
JavaScriptによる日付・時刻・時間の計算・演算のまとめ

12
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
14