"JS Module Pattern"

by Markus

HTML

<p>
  An oversimplified example to show that Both Implementations can be used in the same way.
</p>

JavaScript

// Scroll to the bottom to see the usage of both implementations.

// Own approach.
var smath1 = new function() {
  // "private fields"
  var answer = new Number(42);

  // "public fields"
  this.PI = new Number(3.141592653589793);

  // "private functions"
  function getHalfTheAnswer() {
    return answer / 2;
  };

  // "public functions"
  this.sum = function(a, b) {
    return new Number(a) + new Number(b)
  };
  this.mul = function(a, b) {
    return new Number(a) * new Number(b)
  };
  this.getTheAnswer = function() {
    return answer;
  };
  this.calcTheAnswer = function() {
    return getHalfTheAnswer() * 2
  };
}

// Follwoing the pattern from http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html.
var smath2 = (function() {

  var my = {};

  // "private fields"
  var answer = new Number(42);

  // "public fields"
  my.PI = new Number(3.141592653589793);

  // "private functions"
  function getHalfTheAnswer() {
    return answer / 2;
  };

  // "public functions"
  my.sum = function(a, b) {
    return new Number(a) + new Number(b)
  };
  my.mul = function(a, b) {
    return new Number(a) * new Number(b)
  };
  my.getTheAnswer = function() {
    return answer;
  };
  my.calcTheAnswer = function() {
    return getHalfTheAnswer() * 2
  };

  return my;
}());

// Just an Example to show that Both Implementations can be used in the same way.
console.log("my answer: " + smath1.getTheAnswer());
console.log("the pattern's answer: " + smath2.getTheAnswer());