The first thing to know is:
//your code here....
This is nothing but a self executing anonymous function. All it does is, it simply executes whatever code you write inside it and disappears after that. The private variables declared inside this function are not exposed to the global scope, unless specifically attached to the window object.
return new PrivateSpace();
console.log('init this:', this);
console.log('make ajax calls here');
console.log('cache selectors here');
In the above code, "PrivateSpace" is a private function which is prototyped with our desired functions. "mySpace" is a function which returns a new instance of "PrivateSpace" when executed.
As said before, our anonymous function executes once and does not expose these functions to the outer world. To expose our functions under a namespace, we should add the instance of our "PrivateSpace" to a window level(global) object. This is exactly what the last line of the code does.
So, when we say
we are executing "mySpace()", which returns a new instance of "PrivateSpace()" function and assigning it to "my$", which is a window level object. So if you print my$ like:
, you would get all the functions present in the "PrivateSpace()" prototype. So you can call your functions like: my$.ajax(), my$.cache() etc.
Note that each function in "PrivateSpace()" returns "this". i.e., each function returns an instance of "PrivateSpace()" and hence you can chain your methods like:
Do you have better ideas? Please let me know.
Happy coding :)