Skip to content

Instantly share code, notes, and snippets.

@simondell
Last active January 1, 2016 17:59
Show Gist options
  • Save simondell/8180606 to your computer and use it in GitHub Desktop.
Save simondell/8180606 to your computer and use it in GitHub Desktop.
A simplistic pattern for objects with private members
var Obj = function () {
return {
foo : foo,
foop : foo,
bar : bar
}
// private functions
function foo () { console.log('foo') }
function bar () { console.log('bar') }
}

The function returns an object whose members point to function expressions or to private functions

Code consuming Objs works with the object returned by the function

New instances can be created by calling Obj()

  • I think this makes Obj a "factory" rather than a "constructor"
  • instances are separate, with no shared members
  • I think the private functions are recreated every time: Although they behave like "static functions", they are in fact "private instance functions"
  • (oddly, new Obj() also works but when I first started scribbling this it didn't seem to be so)

Private functions can't be overwritten from outside so they can expect one another to be stable

However, public functions can be redefined from the outside, and because there's no access to the private functions the API for that instance will have changed permanently.

Private functions have no concept of the current object - so when they need to they need to be called by foo.apply( this, args ) or have 'this' passed to it from an anonymous function assigned to the API e.g. return { foo: function ( args ) { foo.apply( this, args ); } }

  • the latter is my preference, but in writing it here I realise how complicated it is and how it's probably slowest because it's a function expression calling a function declaration

The pattern shows these particular coding styles:

  • private functions AFTER the API (other patterns can exploit this too)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment