モジュールパターン練習

by yshrkn

JavaScript

(function() {

  var MYAPP = MYAPP || {
    util: {
      math: {}
    },
    data: {
      int: {}
    }
  };

  MYAPP.util.math = (function() {

      add = function(x, y) {
        return x + y;
      },
      minus = function(x, y) {
        // xがyより大きい時は「x-y」を、そうでない場合は「y-x」を返します
        return x > y ? x - y : y - x;
      },
      multiply = function(x, y) {
        return x * y;
      },
      divide = function(x, y) {
        // yが0のとき「NaN(Not a number)」を返します
        return y !== 0 ? x / y : "NaN";
      }

      return {
        add: add,
        minus: minus,
        multiply: multiply,
        divide: divide
      }

  })();

  function init() {
    var x = 10,
        y = 2;
    console.log(x + "+" + y + "=" + MYAPP.util.math.add(x, y));
    console.log(x + "-" + y + "=" + MYAPP.util.math.minus(x, y));
    console.log(x + "*" + y + "=" + MYAPP.util.math.multiply(x, y));
    console.log(x + "/" + y + "=" + MYAPP.util.math.divide(x, y));
  }

  init();

})();