Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Describe the oft quoted disadvantage of Revealing Module Pattern with an example

I read Javascript Design Patterns, and then a bunch of SO answers on RMP, and I keep finding that where disadvantage is mentioned, it's the straight up quote from the book:

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.

Public object members that refer to private variables are also subject to the no-patch rule.

As a result of this, modules created with the Revealing Module pattern may be more fragile than those created with the original Module pattern, so care should be taken during usage.

Sorry that I'm stupid but the above explanation just isn't doing it for me. Can someone provide a code-rich visual example of what that disadvantage means?

like image 525
james Avatar asked Nov 08 '22 14:11

james


1 Answers

I think this explains the oft-quoted disadvantage. Personally, I don't think this is that big of a deal if you favor composition over inheritance as it simply won't come up.

var revealed = (function() {      
  function foo() {
    return baz();
  }

  function bar() {
    return "I am the original bar!";
  }

  // private function always calls bar because it's in the closure
  // and it can't see the "instance" variable
  function baz() {
    return bar();
  }

  return { foo : foo, bar : bar }
})();

var child = Object.create(revealed);

child.bar = function() {
  return "I am the new bar!";
}

// we want this to call the new bar but it doesn't
console.log(child.foo()); // I am the original bar!

Hope this helps!

like image 153
Guy Royse Avatar answered Nov 13 '22 16:11

Guy Royse