Javascript: What Does This Code Do?
<p>I apologize in advanced if this question is too broad. In fact it's 4 different questions, but all related to the same piece of code, and I think they all revolve around the same principle.</p>

<p>I decided today, after using JS for years, to actually start learning how JS works instead of treating it like C that runs in the browser. So I starting digging into the jQuery code to see how real JS developers use the langauge. That's when I found a block of code that looks like the code below. Note, I took this code off another stacked post here <a href="http://stackoverflow.com/questions/779880/in-javascript-can-you-extend-the-dom">http://stackoverflow.com/questions/779880/in-javascript-can-you-extend-the-dom</a> . So that doesn't mean the person that wrote this code even knew what he was talking about.</p>

<pre><code>var myDOM = (function(){ // #1
    var myDOM = function(elems){ // #2
            return new MyDOMConstruct(elems);
        },
        MyDOMConstruct = function(elems) {
            this.collection = elems[1] ? Array.prototype.slice.call(elems) : [elems];
            return this; // #3
        };
    myDOM.fn = MyDOMConstruct.prototype = {
        forEach : function(fn) {
            var elems = this.collection;
            for (var i = 0, l = elems.length; i &lt; l; i++) {
                fn( elems[i], i );
            }
            return this;
        },
        addStyles : function(styles) {
            var elems = this.collection;
            for (var i = 0, l = elems.length; i &lt; l; i++) {
                for (var prop in styles) {
                    elems[i].style[prop] = styles[prop];
                }
            }
            return this;
        }
    };
    return myDOM; // #4
})();
</code></pre>

<p>1 Why declare the function using var myDOM = (function() {})(); instead of var myDOM = function() {};</p>

<p>2 Why declare <em>another</em> function inside of the myDOM function with the exact same name? Why not put all the inner myDOM's logic inside the outer myDOM function?</p>

<p>3 Why explicitly return "this"? That would have been done automatically, correct?</p>

<p>4 What's going on here? Is it returning the inner myDOM's constructor? If so, why?</p>

<p><strong>Update</strong></p>

<p>So most of it makes sense now. Regarding #1, I thought myDOM was being assigned the function defined after the =, but it's not. It's being assigned whatever that function returns. Which just happens to be a function.</p>

<p>I'm still not clear on #3. Yes, I understand using the function like this</p>

<pre><code>console.log(MyDomConstruct('foo'))
</code></pre>

<p>Would display 'undefined'. But that's not how it's being used. A few lines up is this</p>

<pre><code>return new MyDomConstruct(elems);
</code></pre>

<p>I can understand explicity returning "this" if the statement went like this</p>

<pre><code>return MyDomConstruct(elems);
</code></pre>

<p>But that's not the case.</p>
