The global scope in Javascript (in a browser at least) is window
. So what you've done is you've attached myiife
to window and myiffe
has a function called myFunction
. So if you want to call it from the global scope (i.e. window
) then, of course, you need to specify myiffe.myFunction()
.
What you may have seen other people do is something like this:
var myFunction = (function() {
var counter = 0;
return function() {
counter++;
console.log(counter);
};
})()
Where they have an IIFE return something (in this case a function, in many other case people will return an object). In this case, since myFunction
is a global variable, they can call it with just myFunction()
. What they have achieved with the IIFE is to basically make the counter
variable private. Only things inside the IIFE have access to it.
Of course, if you don't define myFunction
inside of an IIFE, then it will just be a function in the global scope and can be called directly from the global scope.
function myFunction() {
// do something
}
myFunction();
But to your question on using this in an event handler - better practice would be to not inline your event handler in your HTML in the first place and instead bind it in code. This gives you more flexibility, cleaner separation and more maintainable code.