1

hey guys i am just trying to understand the REVEALING MODULAR PATTERN, i see the following simple depiction of the revealing modular pattern:

var myRevealingModule = (function () {

        var privateCounter = 0;

        function privateFunction() {
            privateCounter++;
        }

        function publicFunction() {
            publicIncrement();
        }

        function publicIncrement() {
            privateFunction();
        }

        function publicGetCount(){
          return privateCounter;
        }

        // Reveal public pointers to
        // private functions and properties

       return {
            start: publicFunction,
            increment: publicIncrement,
            count: publicGetCount
        };

    })();

myRevealingModule.start(); 

now the following disadvantages are stated of the revealing moduar pattern ::

A disadvantage of this pattern is that if a private function refers to a public function, that public function can't be overridden if a patch is necessary. This is because the private function will continue to refer to the private implementation and the pattern doesn't apply to public members, only to functions.

i don't quite understand what the above para means , can somebody explain ? private function refers to the public function , did't quite get that , can somebody break it down ?

Alexander Solonik
  • 9,838
  • 18
  • 76
  • 174

1 Answers1

2

Consider:

Mod = function() {
  
  
  function inc() {
    return value() + 1;
  }
  
  var value = function() { return 42 }
  
  var valuePlusOne = function() { return inc() }
  
  return {
    value: value,
    valuePlusOne: valuePlusOne
  }
}()

document.write(Mod.valuePlusOne()) // 43

Mod.value = function() {
  return 999
}

document.write(Mod.valuePlusOne()) // still 43, not 1000

The problem is that inc uses var value from its containing scope, not the value property of the module object. When you change the module, this doesn't affect var value from the scope.

A workaround is to bind private functions to the object being returned:

Mod = function() {
  
  var value = function() { return 42 }
  
  var valuePlusOne = function() { return inc() }
  
  var me = {
    value: value,
    valuePlusOne: valuePlusOne
  }
  
  function inc() {
    return me.value() + 1;
  }
  
 
  return me;
}()

document.write(Mod.valuePlusOne()) // 43

Mod.value = function() {
  return 999
}

document.write(Mod.valuePlusOne()) // 1000
georg
  • 211,518
  • 52
  • 313
  • 390