I have a decent feel for scope and execution flow, but I'm having trouble grasping why this doesn't work:
var modalWindow = (function() {
// Other code...
modalBtn.addEventListener('click', modalWindow.closeModal);
return {
closeModal: function() {
modalContainer.remove();
}
}
}());
And this does:
var modalWindow = (function() {
// Other code...
modalBtn.addEventListener('click', function() {
modalWindow.closeModel());
});
return {
closeModal: function() {
modalContainer.remove();
}
}
}());
The first throws modalWindow
is undefined. I know I could just declare a named object and place closeModal
in it, then reference it, and I wouldn't need the anonymous function in the listener. But I'm curious as to why the latter works as is.
The code you provided has an unmatched (
.
I'm betting the end really looks something like:
})();
The value of modalWindow
is the return value of the IIFE … but it doesn't get that value until the IIFE has finished executing and actually returned a value.
Until then, the value is undefined
so when you try to read it before the IIFE is finished, it errors.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.