简体   繁体   中英

Javascript revealing module pattern disadvantages

I have been reading about revealing module pattern in Addy Osmani's book. It highlights following disadvantage:

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 which refer to private variables are also subject to the no-patch rule notes above.

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.

I'm not an expert in JS and it is not making much sense to me. Also book doesn't provide any examples of these disadvantage comparing to module pattern .

I googled and found this on here:

Revealing module pattern disadvantages

which again I'm not able to grasp. As examples being used are using constructor functions.

Could someone please ELI5 please.

This could be understood by the code below.

    var myRevealingModule= (function(){

        let privateVar = 'Kirti';
        let publicVar ='Hye there';

        function getName () {
            console.log('name is ' + privateVar);
        }

        function privateGetNames(){
            getName()
            sayGreeting();
        }

        function sayGreeting() {
            console.log(publicVar);
        }

        return {
            getname: privateGetNames,
            sayGreeting: sayGreeting
        }
    })();


 //earlier result 
myRevealingModule.getname();
//overriding a public method    
myRevealingModule.sayGreeting = () => console.log('helloooo change');
    myRevealingModule.getname();

in this myRevealingModule has a private method privateGetName which access sayGreeting a public Method and now if I want to override sayGreeting later (like I did above) the privateGetName will continue to access its private sayGreeting not the overridden sayGreeting that we declared later.

hence its very difficult to patch these public methods

There is a very nice article which can help you on with detailed explaination. https://developerslogblog.wordpress.com/2017/10/22/drawbacks-in-the-javascript-module-pattern/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM