I found I could use this technique to retain a sort of “state” within an event handler, w/o having to involve outside variables…
I find this technique to be very clever in leveraging the fact that functions are actually objects in and of themselves, but am worried I’m doing something that could have negative implications of some sort…
Example…
var element = document.getElementById('button');
element.onclick = function funcName() {
// attaching properties to the internally named "funcName"
funcName.count = funcName.count || 0;
funcName.count++;
if (self.count === 3) {
// do something every third time
alert("Third time's the charm!");
//reset counter
funcName.count = 0;
}
};
Instead of doing that, you can use a closure:
That setup involves an anonymous function that the code immediately calls. That function has a local variable, “count”, which will be preserved over the succession of event handler calls.
By the way, this:
is “dangerous” because some browsers (guess which, though Safari has had issues too) do weird things when you include a name on a function expression like that. Kangax wrote the issue up quite thoroughly.