What is the recommended approach for helper functions? I would like to choose one technique, and run with it to create my new "class".
Here are the design options I have pondered:
Option 1: Helper function in outer scope, invoke with context of instance
function createPane (pane) {
// logic to create pane
var proto = Object.create(this.paneList);
$.extend(paneProto, pane);
return paneProto;
}
Panes.prototype.initialize = function (panes) {
var _this = this;
_.each(panes, function () {
_this.panes.push(createPane.call(_this, this));
});
}
- Pros: Simple syntax.
createPane
is not published on the instance. - Cons:
createPane
is accessible in other scopes.
Option 2: Helper function in closure, invoke with context of instance
Panes.prototype.initialize = (function () {
function createPane (pane) {
// same logic as last createPane
}
return function (panes) {
// same logic as before - calls createPane
}
})();
- Pros:
createPane
is not published on the instance. - Cons: Lower readability and testability; Testing of this helper must occur in the scope of initialize.
Option 3: Prepend _ to name to indicate a private method
Panes.prototype._createPane = function (pane) {
// same logic as last createPane
}
Panes.prototype.initialize = function (panes) {
// same logic as last, except calls this._createPane
}
- Pros: Implicit context of
_createPane
is the instance. Testability from the outside. - Cons: Exposing helper function on the instance.
Option 4: Helper functions as arguments
Panes.prototype.initialize = (function (createPane) {
return function (panes) {
// same logic as before - calls createPane
}
})(function createPane () {
// same logic as last createPane
});
- Pros:
createPane
is not published on the instance. Helper functions lack access to each other. - Cons: Lower readability and testability; Testing of this helper must occur in the scope of initialize.