Reputation: 1742
I have not used javascript that much, so I'm confuse about the following code structure. The code is from an external javascript file and the init function was called from index page as "windows.Ux.init(xxx)". I know it's self-invoking function and I assume "windows" object is passed as a parameter to that function. And I assume "exports.Ux" line declares name space and assigned functions to the two variables in the namespace. Are my assumptions correct?
( function( exports ) {
...
function init(x) {
...
}
..
exports.Ux = {
init: init,
clear: clear
};
})( window );
Upvotes: 0
Views: 71
Reputation: 30330
This snippet defines a function:
(function( exports ) {
// ...
})
And immediately calls it with the argument window
:
(function ...)(window);
You can think of the effect of this call as:
init
and clear
exports.Ux
.Your function takes a single argument called exports
, and you call it with the single argument window
, so you can think of the immediately-invoked function call doing this:
window.Ux = {
init: init,
clear: clear
}
window
is the global root object in a web browser JavaScript environment.
Upvotes: 3
Reputation: 1074238
I know it's self-invoking function...
It's an immediately-invoked function expression (an "IIFE"). (A self-invoking function would be recursive.)
...and I assume "windows" object is passed as a parameter to that function.
The value of the window
global is passed into it, yes. On browsers, that's a reference to the global object. that value is received in the function's exports
argument.
And I assume "exports.Ux" line declares name space and assigned functions to the two variables in the namespace.
No, it creates an object that is accessible via the Ux
property on the object exports
refers to (which is the global object in that case). The object Ux
refers to has properties referring to functions (loosely, "methods").
Upvotes: 3
Reputation: 23632
This is called IIFE
:
( function( exports ) {
...
function init(x) {
...
}
..
exports.Ux = {
init: init,
clear: clear
};
})( window );
exports.Ux
is what your exposing, meaning anything which is not part of exports.Ux
is not available outside. Encapsulation
. So if your IIFE has the following structure:
( function( exports ) {
...
function init(x) {
//you can use it here somePrivate()
...
}
function somePrivate(){
}
..
exports.Ux = {
init: init,
clear: clear
};
})( window );
The somePrivate
function is not exposed to outside world via window
object, though you can use it inside your other function
.
Upvotes: 3