-
-
Save joseph/9766225 to your computer and use it in GitHub Desktop.
// 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; | |
}); |
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
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;
});
K is for Class (and Constants!).
I is for Instance (and Interface!).
P is for Properties (and Private!).