taquaki-satwo
11/27/2017 - 3:04 PM

モジュールパターン #2

JS-モジュールパターン #2

// モジュールパターン ES5
// 名前空間を準備
var MYAPP1 = MYAPP1 || {
  util: {
    math: {}
  },
  data: {
    int: {}
  }
};

// 即時関数でモジュールを定義する
MYAPP1.util.math = (function() {
  
  // プライベートメンバーの定義
  var add = function(x, y) {
    return x + y;
  },
  minus = function(x, y) {
    return x > y ? x - y : y - x;
  };
  
  // public API
  return {
    add: add,
    minus: minus
  }
}());

// モジュールを使う
console.log(MYAPP1.util.math.add(2,5));
console.log(MYAPP1.util.math.minus(2,5));

JS-モジュールパターン #2

A Pen by Takaaki Sato on CodePen.

License.