Why declare a function with var myDOM = (function () {}) (); instead of var myDOM = function () {};
This is called a self-invoking anonymous function or self-executing anonymous function . He does just that, he calls himself at runtime. You will also see a template:
(function($){ }(jQuery));
quite a lot in the jQuery world. The same thing, at runtime, the function calls itself and ensures that the $ sign has a reference to the jQuery object inside the function body.
In your fragment, the function calls itself and returns a myDOM function reference.
Why declare another function inside the myDOM function with the same name? Why not put all the internal logic of myDOM inside the external function myDOM?
This is just an agreement. It could be called what you want, perhaps the author thought it was convenient to do. The reason for this pattern is privacy and security. myDOM returning the internal myDOM reference, a closure is created. So, after declaring something like
var mytest = myDOM([]);
you will not have access to MyDOMConstruct , but your internal function has access. This way you can protect your methods and variables. It is also called method pattern . It is always good to read in this context Douglas Crockford: Javascript the good parts .
Why do I explicitly return "this"? That would be done automatically, right?
No, the function will return undefined by default. Explicitly returning this , you can chain use the following methods (from the above call):
mytest.forEach([]).addStyles([]); ...
since each method returns a call object, in this case myDOM .
What's going on here? Does it return the internal constructor myDOM? If so, why?
Hope this should be clear at this point.
Edit
Based on your update:
new MyDOMConstruct();
creates a new object that inherits from
MyDOMConstruct.prototype
Without a new keyword this will not be bound to a new object. Instead, it will be bound to a global object (window), and you will access global variables using this .