views:

103

answers:

3

nextplease.init = function() {...} is a function with no arguments. I'd expect nextplease.init and function() {nextplease.init();} to behave identically. Is there any possible difference between them (obviously, you can assign something to nextplease.init, but let's exclude that)? In particular, can there be a difference in behavior between window.addEventListener("load", nextplease.init, false); and window.addEventListener("load", function() {nextplease.init();}, false);?

The bug I'm trying to find is described in http://stackoverflow.com/questions/2314961/objects-in-javascript-defined-and-undefined-at-the-same-time-in-a-firefox-extens Someone has suggested that using the first form instead of the second might make a difference.

A: 

There are 2 possible differences

window.addEventListener("load", nextplease.init, false);

This will call the function and that is all. If you wanted to add parameters, then this wouldn't be able to set them.

window.addEventListener("load", function() {nextplease.init();}, false);

This, on the other hand, allows you to call more than one function, and allows you to set parameters. It also adds extra overhead of calling a function, and storing a function in memory.

Gabriel McAdams
A: 

These two:

window.addEventListener("load", nextplease.init, false); 
window.addEventListener("load", function() {nextplease.init();}, false);?

are almost exactly the same, assuming nextplease.init is a function object.

The one difference is that in the second case, any arguments passed to the outer function (even though its signature doesn't define any, they can still be passed) will not get passed to nextplease.init(). But since this is just going through the addEventListener API, you know what will be passed ahead of time.

friedo
+4  A: 

One important difference is the value of the "this" keyword inside the body of the function referenced by nextplease.init.

Assume nextplease is defined as such:

nextplease = {};
nextplease.someCustomProperty = "hello";
nextplease.init = function () { alert(this.someCustomProperty); }

In the first example, the value of "this" would be the DOM object, and the alert would fail:

window.addEventListener("load", nextplease.init, false);     

In the second form, the value of "this" would be the nextplease object, and the alert would say, "hello":

window.addEventListener("load", function() {nextplease.init();}, false);

Reference the MDC documentation:

https://developer.mozilla.org/en/DOM/element.addEventListener

Jeff Meatball Yang