简体   繁体   English

从点击侦听器调用公共方法时,为什么需要匿名函数来封装

[英]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.

相关问题 为什么我必须在匿名函数中包含Javascript函数调用才能立即调用它? - Why do I have to enclose a Javascript function call in an anonymous function for it to not be called immediately? Polymer 2.0:为什么强制添加侦听器时为什么需要匿名函数 - Polymer 2.0: why do we need an anonymous function when imperatively adding listener 需要帮助调用带有单击事件侦听器的方法 - Need help calling a method with a click event listener 为什么从匿名函数调用方法时这是对象,但直接调用会引发错误 - Why when calling a method from a anonymous function this is the object but a direct call throws an error 为什么我必须将函数包含在另一个函数中? - Why do I have to enclose a function in another function? 访问匿名自执行函数的参数时,为什么需要使用“ this”关键字? - Why do I need to use the “this” keyword when accessing a parameter for an anonymous self-executing function? 为什么我需要将匿名函数传递给onClick事件? - Why do I need to pass an anonymous function into the onClick event? 为什么我需要在setTimeout中使用匿名函数才能使此代码生效? - Why do I need to have anonymous function in the setTimeout for this code to work? 删除事件侦听器 - 我是否需要传递完全相同的匿名 function? - Removing Event Listener - Do I need to pass the exact same anonymous function? 通过匿名函数包含对象时,显示错误消息 - When enclose an object by anonymous function, show me error message
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM