开发者

Function values in JavaScript

nextplease.init = function() {...} is a function with no arguments. I'd expect nextplease.i开发者_开发技巧nit 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.


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜