I had this code:
Javascript
(function() {
function read() {...}
})();
HTML
<body onload="read()">
Console said, read is undefined
.
After deleting the IIFE it worked, why?
Thanks. :)
I had this code:
Javascript
(function() {
function read() {...}
})();
HTML
<body onload="read()">
Console said, read is undefined
.
After deleting the IIFE it worked, why?
Thanks. :)
Here's a long but satisfying explanation about JavaScript scope and closures.
Since you declare read
inside a function, it is local to that function.
Anything you declare inside a function will be local to it.
You can explicitly put it into global scope by assigning it as a property to window
:
(function() {
function read() {...}
window.read = read;
})();
Writing
(function() {
function read() { ... }
})();
Is very nearly the same thing as writing
(function() {
var read = function() { ... } //this is different, but not significantly so
//for purposes of teaching this point
})();
and I think you should already understand why a var
declared inside a function is not available outside of that function's scope.
The behavior of a function definition (function read() { ... }
) is slightly different from the behavior of assigning a function expression to a variable (var read = function() { ... };
) in terms of when the name of the function and the function become associated, but the two are otherwise identical.
Because it isn't defined globally. It's only been defined within the scope of that immediately invoked function. To make it global either use this:
function read() {...}
(function() {
...
})();
Or this:
(function() {
window.read = function() {...}
})();
Or better yet, just bind the onload
event within the immediately invoked function:
(function() {
function read() {...}
window.onload = read;
})();
In this case the definition of read
is inside the IIFE. This limits the scope of the function to the IIFE and any child functions inside of it. The handler for onload
is executed in the global scope and hence doesn't have access to read