Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function values in JavaScript

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 Objects in JavaScript defined and undefined at the same time (in a FireFox extension) Someone has suggested that using the first form instead of the second might make a difference.

like image 405
Alexey Romanov Avatar asked Feb 23 '10 17:02

Alexey Romanov


1 Answers

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

like image 152
Jeff Meatball Yang Avatar answered Oct 06 '22 00:10

Jeff Meatball Yang