开发者

Why, in Apple's Safari Developer Library, do they use anonymous functions when attaching eventsListeners?

All,

I'm pretty new to JavaScript development, so this is probably a very stupid question.

But, I'm reading Apple's Safari Developer Library, and I notice that they use "anonymous functions" when attaching eventListeners:

this.element.addEventListener('touchstart', function(e) { return self.onTouchStart(e) }, false);

Is this any different t开发者_JAVA技巧hen this:

this.element.addEventListener('touchstart', onTouchStart, false);

Assuming it is different, how? If it's not, why do they use this method?

Here's a link to the document I'm referring to:

Safari Developer Guide - Interactive Visual Effects

Some clarification...

I would understand the benefit of this:

this.element.addEventListener('touchstart', function(e) { alert("touched")}, false);

Over this...

this.element.addEventListener('touchstart', onTouchStart, false);
function onTouchStart(e) {
    alert("touched");
}

In this case, you've saved creating a "permanent", named function.

But, in Apple's case, the function named "onTouchStart" is a permanent, named function either way. So, is there still a benefit?

Thanks in advance!


Your way works as long as you don't need to access any members of the "self" object, or supply any other parameters. Generally, you do, though, so the technique they use creates a closure which will would allow you to access local variables (such as "self", which is typically just a reference to "this" in the calling function)


It's a very simple function that only has to do one thing and isn't used anywhere else. Naming it is simply unnecessary when you don't have to. The code is cleaner and simpler if you don't, though both methods are equivalent. To be precise, the first is the same as:

function onTouchStart(e) {
    return self.onTouchStart(e);
}
this.element.addEventListener('touchstart', onTouchStart, false);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜