Javascript object style

joseph edited this page Sep 4, 2011 · 1 revision

In this incarnation at least, Monocle uses a Javascript idiom for defining many of the core classes. This is designed to declutter the classes, clarify their API, and reduce dependency problems that would constrain the progress of the project.

Essentially, the constructor function returns not the instance itself, but an object that references the public methods and properties of that object.

The class idiom looks like this:

Monocle.Foo = function (args) {
  // Allows the constructor function to be an object factory itself,
  // ie: "Monocle.Foo()" is the same as "new Monocle.Foo()".
  // (Only necessary for classes that a library user may instantiate.)
  if (Monocle == this) { return new Monocle.Foo(args); }

  // Conventional name for the object that is returned by the constructor,
  // allowing access to the public methods and properties by external code.
  var API = { constructor: Monocle.Foo }

  // Conventional name for any class constants. Typically this is the
  // class constructor function itself.
  var k = API.constants = API.constructor;

  // Conventional name for any publicly accessible properties (instance
  // variables).
  var p = API.properties = {
    someVariable: 'bar'
  };


  // A method that will be exposed via the API.
  function examplePublicMethod() {
  }


  // A method that is only available to code within the constructor itself.
  function exampleInternalMethod() {
  }


  // Typically, public methods are attached to the API just before
  // returning, for easier scannability of the API.
  API.examplePublicMethod = examplePublicMethod;

  return API;
}

// Defining some "constants" on the class. (Of course, not really constant.)
Monocle.Foo.A_CONSTANT = 'Foo';
Monocle.Foo.PI = 3.14;

This allows a quite concise, clear coding style. There's a trade-off against class inheritance, but JS offers other ways to share logic between classes.