2

I know there is a great difference in 2 methods below:

a.onclick = function() {alert("Hi");};

and

a.onclick = (function() {alert("Hi");};)();

Why do people use the second method? The second should fire the alert() on page load but doesn't?

Why in Difference between onbeforeunload and onunload does the first guy uses the anonymous and the second uses the right one?

Community
  • 1
  • 1
Samul
  • 1,824
  • 5
  • 22
  • 47

3 Answers3

4

There are times when an anonymous, self-executing function is useful for event handlers. Your scenario is not one of them.

Here's one example. In this example, I'm using a scoped variable to keep track of how many times the handler is invoked, but in order to keep that variable from leaking into the outer scope, it has to be in a function; but in order to persist the value across event handler calls, it can't be initialized in the handler itself-- it needs to be bound in a closure.

a.onclick = (function () {
    var counter = 0;
    return function (e) {
        ++counter;
        alert("Hi! This handler has been invoked " + counter + " times!");
    };
}());

So the self-executing function itself returns a function which is suitable as an onclick handler. However, it also has its own static state that it needs to keep track of even between invocations.

This is just one example of why it might be useful to use a self-executing function that returns a function for an event handler or other callback slot.

Platinum Azure
  • 45,269
  • 12
  • 110
  • 134
2

You will probably get what you want by using the first method, i.e. storing a function in onclick field of object a.

The second case before storing invokes that function, which returns undefined, so it is equivalent of

a.onclick = undefined;
pepkin88
  • 2,742
  • 20
  • 19
0

For those who find the whole anonymous function thing unreadable:

a.onclick = a_onclick;
var counter = 0;
function a_onclick()
{
  counter++;
  alert("Hi! This handler has been invoked " + counter + " times!");
}

jsfiddle: http://jsfiddle.net/stevenally/aXKL7/

stevenally
  • 89
  • 1
  • 4