Onclick event getting called automatically

You’re calling the function right away.

When you leave the parentheses on the function reference, what you’re basically saying is:

Evaluate the closeThis function and assign the result to onclick

when what you really want to do is assign the function reference to the click handler:

document.getElementById("closeButton").onclick = myclassObj.closeThis;

Leave out the parentheses instead, and you’ll bind the closeThis function to the onclick. What this instead says is:

Assign the function closeThis to the click handler.

You are essentially assigning the function to the variable as a first-class object, or a reference to a function.

As an aside, my personal preference is to always use an anonymous function wrapper. Sometimes you need to be able to pass parameters into your function, and this makes sure that you can more easily do so:

document.getElementById("closeButton").onclick = 
    function() {
        myclassObj.closeThis();
    };

Leave a Comment