Skip to content

Instantly share code, notes, and snippets.

@joseph
Last active August 29, 2015 13:57
Show Gist options
  • Save joseph/9766225 to your computer and use it in GitHub Desktop.
Save joseph/9766225 to your computer and use it in GitHub Desktop.
JS class pattern [1] — "KIP"
// AMD module definition:
define(function (require) {
// An instantiable class:
var K = function () {
// This represents the public interface for the object.
var I = this;
// Properties of the object:
var P = I._p = {};
// A private method:
function initialize() {
}
// A public method:
I.update = function () {
}
initialize();
};
// A constant
K.MEANING_OF_LIFE = 42;
return K;
});
@joseph
Copy link
Author

joseph commented Mar 25, 2014

By not using prototypical definitions (K.prototype.update = function () { ... }) we take a bit of a memory hit, since identical public methods are not shared between instances. However, the benefit is that we can call private methods from our public ones.

A contrasting proposal, perhaps more conventional: https://gist.github.com/joseph/9766958

@danshultz
Copy link

While I prefer the other pattern for what I mentioned, if going this route, I would opt more something along the following as I think it makes it simply to follow and grok

methods that are not part of the public interface still are prefixed with an underscore, the public interface is exposed using a return statement at the end but you also know it when digging through the code because public methods do not have an underscore around them.

The bigger plus to this pattern is people do not have to understand "this" but I think having the option to rebind contexts is powerful.

// AMD module definition:
define(function (require) {

  // An instantiable class:
  var K = function () {

    // Properties of the object:
    var props = {};

    // A private method:
    function _initialize() {
    }


    // A public method:
    function update () {
    }


    initialize();

    return {
      update: update
    }
  };


  // A constant
  K.MEANING_OF_LIFE = 42;

  return K;

});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment