Object-oriented – Best JavaScript Coding Structure Using Object Literal

javascriptjqueryobject-oriented

Object Literal has no doubt been established in recent years as one of the essential components to best JavaScript coding practices. However, I am not very sure about what is the best way to structure my codes using Object Literal.

It has been suggested earlier before that Module Pattern might be a good technique to structure your codes [1] [2], but criticisms regarding Module Pattern have begun to surface as people spent more times exploring the extent of the technique. [3] [4]

So, my question is: as of summer 2011, what is the acknowledged best way to structure your codes utilizing Object Literal? Is it still Module Pattern, or has some other technique emerged already as a yet better replacement?

Best Answer

The module pattern can be nice for certain things, but you should really consider whether you really need your properties to be private. If it is really necessary to make your properties private, then by all means, use the Module pattern:

var namespace = (function(){ 
  var a = {
    internalFunction: function (number) {/*Do internal stuff*/},
    internalVariable: 365,
    publicFunction: function() { return internalFunction(internalVariable) },
  }
  return {
    publicFunction: a.publicFunction
  }
}();

If you don't mind all of your functions being accessible, just use this simpler form:

var namespace = {
  noLongerInternalFunction: function(number) {/*Do stuff*/},
  noLongerInternalVariable: 365,
  stillPublicFunction: function() { 
    return noLongerInternalFunction(noLongerInternalVariable); 
  }
}
Related Topic