how to use the javascript module pattern in a real example?

后端 未结 5 1968
陌清茗
陌清茗 2021-01-31 05:59

I am trying to understand the JavaScript Module Pattern. I\'ve seen examples of what it should look like, but I don\'t understand how to use it.

For example, a few thing

5条回答
  •  自闭症患者
    2021-01-31 06:48

    I've got some experience with Mootools, but I'm a jQuery novice. I've read through the docs, and it looks like the smartest way to organize code is the Module Pattern, so I'm trying that out. However, one thing that seems to be missing from that style is any notion of "self", since each variable within the IIFE is a self-contained object (no pun intended).

    So...maybe this defeats the whole purpose, but could you do something like this, and still have it be "valid" in all the ways that the module pattern style is valid?

    var feature = ( function () {
    
        var self = {
    
            config: {
                option1: 'thing 1',
                option2: 'thing 2'
            },
    
    
            init: function (options) {
    
                // allow overriding the default config
                jQuery.extend( self.config, options );
    
                self.doSomething();
    
            },
    
            doSomething: function () {
    
            },
    
        };
    
        return {
            init: self.init
        }
    
    })();
    

    What I like about this is that I can internally reference all of the methods and properties using "self". I'm still able to expose the methods that I want using the "return" object, so (I guess) that's okay. But I'm such a novice, and this seems so simple and (at first glance) elegant, that I must be missing a major gotcha. It shares the coding style with the Object Literal format, which is what I'm familiar with from Mootools. So maybe I'm trying to fit a round peg into a square hole. Maybe the internal object literal isn't necessary, because rather than "self.doSomething()", I can just say "doSomething"? Is that the case?

    Partially I like this because I can set the "context" argument of $.ajax to be "self", which seems like a win.

提交回复
热议问题