简体   繁体   English

如何在 IIFE 内部调用函数

[英]How to call function inside the IIFE

<a onclick="testFunction(); return false;">Click me</a>
<script type="text/script">
    (function (){
        var testFunction = function(){
            console.log('From test function');
        };
    })();   
</script>

In the above code, when I click on the hyperlink it is showing testFunction not defined.在上面的代码中,当我单击超链接时,它显示未定义 testFunction。

How do I execute the testFunction without polluting the global name space?如何在不污染全局命名空间的情况下执行 testFunction?

This is why you don't use inline event handling.这就是您不使用内联事件处理的原因。 Define an event handler method inside your IIFE, otherwise the scope is not able to reach and testFunction is undefined.在你的 IIFE 中定义一个事件处理程序方法,否则范围无法到达并且 testFunction 未定义。

<a id="clickMeInstead">Click me</a>
<script type="text/script">
    (function (){
        var testFunction = function(){
            console.log('From test function');
        };
        var link = document.getElementById("clickMeInstead");
        link.addEventListener("click", function() {
            //run code here
        });
    })();   
</script>

Use addEventListener instead of inline events使用addEventListener代替内联事件

var link = document.getElementsByTagName("a")[0];
link.addEventListener("click", function() {
    console.log('From test function');
});

If you just want to prevent testFunction() to pollute the global namespace, you can do a variation of the revealing module design pattern to achieve this by doing the following:如果您只是想防止 testFunction() 污染全局命名空间,您可以通过执行以下操作来实现揭示模块设计模式的变体:

    <a onclick="coverModule(); return false;">Click me</a>

<script>
        function coverModule() {
            return (function testFunction() {
                    alert('From test function');
            })();
        }
</script>

I'd recommend this over using event handlers since DOM manipulation is an expensive operation.我建议不要使用事件处理程序,因为 DOM 操作是一项昂贵的操作。 But please note that this also cannot be considered an optimal solution since inline JavaScript isn't nice.但请注意,这也不能被视为最佳解决方案,因为内联 JavaScript 不好。 It's all about the trade-off you're willing to make.这完全取决于您愿意做出的权衡。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM