[英]Why do I need an anonymous function to enclose when calling public method from click listener
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. 第一个抛出modalWindow
是未定义的。 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. 我知道我只需要声明一个命名对象并在其中放置closeModal
,然后对其进行引用即可,并且在侦听器中不需要匿名函数。 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. modalWindow
的值是modalWindow
的返回值…,但是直到IIFE 完成执行并实际返回一个值后 ,该值才得到。
Until then, the value is undefined
so when you try to read it before the IIFE is finished, it errors. 在此之前,该值是undefined
因此当您在IIFE完成之前尝试读取它时,它会出错。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.