Object, Closure, Module practice in Javascript

Tags:

Based on the code in ‘Javascript: The Good Parts’.

Some doesn’t like the lambda-like structure, and it’s not still clear to me which is better between object oriented pattern like style(prototype) or module like style(the one at the bottom of code snippet below).

It’s good that there is a great flexibility, but it’s not good to force some complex styles to the team which I am work with unless there is a strong reason to do so.

<html>
  <body>
    <pre>
      <script>
        // Constructor
        document.writeln('Constructor');
        var Foo = function(v) {
          this.val = v;
        };
        Foo.prototype.get_val = function () {
          return this.val;
        };
        var f = new Foo('abc');
        document.writeln(f.get_val());

        // Closure
        document.writeln('Closure');
        var foo = function(v) {
          var val = v;
          document.writeln("I am initialized multiple times.");
          return {
            get_val: function() {
              // I have access to outer val.
              return val;
            },
          };
        }();
        var f = foo(7);
        document.writeln(f.get_val());
        var f2 = foo(8);
        document.writeln(f2.get_val());

        // Module
        var bar = function() {
          document.writeln("I am called only once.");
          // See that I'm returning inner function. So, the initialization here
          // happens only once. Thus, this is a good place to run costly commands
          // that can be shared by b and b2 below.
          return function(v) {
            var val = v;
            return {
              get_val: function() {
                return val;
              }
            };
          };
        }();  // Look! I'm calling the function here.
        var b = bar(3);
        document.writeln(b.get_val());
        var b2 = bar(4);
        document.writeln(b2.get_val());
      </script>
    </pre>
  </body>
</html>

Output:
Constructor
abc
Closure
I am initialized multiple times.
7
I am initialized multiple times.
8
I am called only once.
3
4