In this thread I found a JavaScript code snippet which I want to use.
The code looks like:
(function(global) {
// the function code comes here
})(this);
How can i call this function to execute the code? What do I have to pass in for this global
variable?
The function is immediately executed, you do not execute it by calling it.
It is a function literal definition, followed by two parens which causes that function to invoke immediately. Read more: Immediately-Invoked Function Expression (IIFE)
Whatever code you place inside is run right away. Anything placed in the invocation parens is passed into the function as an argument. Assuming your sample code was defined in the global scope, this
is the window
object, and is referenced as global
within the function body. It is a great way to encapsulate your programs to avoid variable collision, force strict mode, and much more.
This construct defines a function:
function(global) {
// the function code comes here
}
and immediately calls it, passing this
as a parameter:
([function])(this)
The identifier global
is simply the name of this parameter inside the function body. For example, try
console.log(this); // outputs something
(function(global) {
console.log(global); // outputs the same thing as above
})(this);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With