2

I usually do component for each feature, says I have abc feature I will create below js

var AbcComponent = (function(){}
   var initialize = function(){

   },
   privateMethod1 = function(){

   };

   return {init:initialize}
)();

and include in app.js, with AbcComponent.init();. Few days ago I ready about OO using object literal pattern and I doubt my own writing style.

How can literal pattern encapsulate scope since javascript is function scope?

1 Answers1

1

All module patterns that need to have truly private data must inherently use an IIFE to maintain their own private scope. Even the object literal module pattern uses this. See a comparison of some module patterns,

You can store pseudo-private data in a couple of ways with an object literal:

By convention, properties that start with an _ underscore are understood to be off-limits to the rest of the world.

{
    _privateBar : 1
    publicFoo : 4,
}

Alternatively, you can use symbols.

const privateBar = Symbol('private');
myModule[privateBar] = 1;
myModule.publicFoo = 4;

Using the latter, only a reference to the privateBar symbol object can get you the value of 1 from myModule. And no, you can't get it with myModule[Symbol('private')], because symbols are unique and Symbol('private') === Symbol('private') is false.

Unfortunately, they decided to add Object.getOwnPropertySymbols(), so an object's symbols are not truly private and are not suitable for protecting data from malicious activity.

However, in practice, most operations you perform (for of loops, etc.) will not touch symbols. And therefor it is an excellent replacement for the underscore _ convention. But sometimes there are even better ways, such as using a WeakMap.

Using ES6 we can actually avoid the slight overhead of an IIFE thanks to lexical scoping.

const myModule = {};

{
    const privateBar = 1;
    myModule.publicFoo = 4;
}
Community
  • 1
  • 1
Seth Holladay
  • 8,951
  • 3
  • 34
  • 43
  • I'm asking how object literal pattern can be used for encapsulation since they are just bunch of objects. – Nately Jamerson Jan 05 '17 at 03:04
  • 1
    @NatelyJamerson I added some more info, including that the so-called "object literal module pattern" still includes an IIFE for encapsulation. If this doesn't do it for you, maybe you could add some links to what you read and what you think the author means or what their code is doing. Then I can explain or correct it with more context. – Seth Holladay Jan 05 '17 at 03:57