Wrapped Function With Global Variable On Window Object
Solution 1:
Can you tell me why do we call the following and how/when does it get executed?
The outer structure in your code is called an Immediately Invoked Function Express (IIFE). It's really just a function definition that is both defined and called all at once without giving it a name. It is executed immediately.
(function(someArg) {
// body of function
}(something));
It's basically like this:
function myFunc(someArg) {
// body of function
}
myFunc(something);
Your IIFE works identically to this above code with the one difference that the IIFE does not assign a name to the function so no name is used within that scope.
In your IIFE, you are passing window.MyApp
to your function which is presumably an object. In the definition of that function, the variable that is passed to the function is given the name myApp
. So, anywhere inside that function where you refer to myApp
, it is essentially an alias for window.MyApp
as they both point to the same object and any change in one is a change to the same object.
Your code is essentially like this:
functionmyFunc(myApp) {
var helperFunction = function() {
//helper function body
};
myApp.Helper = helperFunction;
}
myFunc(window.MyApp);
What is the difference between myApp, and window.MyApp?
There is no difference. They both point to the same object.
Why have we passed myApp, is it actually getting passed from anywhere?
It's a style or design choice to pass it in. It doesn't have to be passed in. It could be referenced as window.MyApp
everywhere in the function if one wanted, but this way, there is a shortcut to use it inside the function as myApp
.
Solution 2:
It's called a self-invoking function. I'm not sure about the exact syntax though :)
To answer your questions:
What is the difference between myApp, and window.MyApp?
myApp is the function argument. window.myApp is what's passed into the funciton.
Why have we passed myApp, is it actually getting passed from anywhere?
See the above answer - hopefully it will clarify what's going on.
Basically, the code is equivalent to saying:
functionmyFunction(myApp) {
var helperFunction = function() {};
myApp.Helper = helperFunction;
}
myFunction(window.MyApp);
Except that it is more concise and doesn't actually declare the function myFunction
.
Post a Comment for "Wrapped Function With Global Variable On Window Object"