javanoob
javanoob

Reputation: 6410

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.

How do I execute the testFunction without polluting the global name space?

Upvotes: 2

Views: 2538

Answers (3)

Anne Bione
Anne Bione

Reputation: 19

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:

    <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. But please note that this also cannot be considered an optimal solution since inline JavaScript isn't nice. It's all about the trade-off you're willing to make.

Upvotes: 1

Richard Hamilton
Richard Hamilton

Reputation: 26444

Use addEventListener instead of inline events

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

Upvotes: 1

Sterling Archer
Sterling Archer

Reputation: 22405

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.

<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>

Upvotes: 6

Related Questions