Reputation: 1191
I have the following simple code:
window.Foo = window.Foo || {};
((Foo) => {
'use strict';
Foo.select = Foo.select || {};
Foo.select.init = (selector, options) => {
...
};
Foo.select.otherInit = () => {
...
};
$((e) => {
Foo.select.init();
Foo.select.otherInit();
});
})(window.Foo);
As I am a js principiant I wonder a couple of things:
First the stupid one: instead of passing Foo
can I access it by this.Foo
inside the function? As I guess so, is it just kind of code style?
what does (window.Foo)
in the last line mean? what's for?
Lastly, why using:
$((e) => {
Foo.select.init();
Foo.select.otherInit();
});
and not just:
Foo.select.init();
Foo.select.otherInit();
thank you!
Upvotes: -1
Views: 104
Reputation: 27194
First the stupid one: instead of passing Foo can I access it by this.Foo inside the function? As I guess so, is it just kind of code style?
Yes, you could access it directly through this.Foo
, but only because the current function-scope is bound to the window
Object (because you are using an arrow function) and because Foo
is part of window
(possibly due to the fact that it was just defined in the global scope).
If you were to try this in a function call inside another object, this.Foo
would fail. I would not recommend doing this, unless you have a good reason to do it this way.
Here can learn more about arrow functions and the this
context.
what does (window.Foo) in the last line mean? what's for?
Your whole construct (see below) is an IIFE: Immediately-invoked function expression. You are using an arrow function, so this binds the context as well (see point above).
The last part, (window.Foo)
, means that you invoke the function you called with the argument window.Foo
, which is then available as Foo
within your function.
((Foo) => {
...
})(window.Foo);
Lastly, why using:
$((e) => { Foo.select.init(); Foo.select.otherInit(); });
and not just:
Foo.select.init(); Foo.select.otherInit();
This is a jQuery function call, which is executed once the DOM is ready. The function within $(...)
is called, once the DOMContentLoaded
event is fired.
If this were not present, the code could be executed before the DOM is ready (thus possibly not finding the DOM elements referenced in those functions). This depends on where you place your javascript code though (if you place it right before </body>
you should be safe).
Upvotes: 1