I’ve been trying to read and understand a bit more about better code and design with Javascript, and really the lack of tutorials explicitly describing about the benifts / uses of creating code in a different way than what a majority of the online code has.
I came across the following code (below) and realized about assigning functions to variables, however am still trying to understand the benifit / how to use this to my advantage.
Is this prototyping, using closure, or just a neat stylized way of doing something instead of doing it in the normal sense of:
Function doThis(el, type, fn){ ... }
My main question is why would you use this method below, and what are the benifits to it?
Thank you in advance your your help and patience.
var addEvent = function() {
if (window.addEventListener) {
return function(el, type, fn) {
el.addEventListener(type, fn, false);
};
} else if (window.attachEvent) {
return function(el, type, fn) {
var f = function() {
fn.call(el, window.event);
};
el.attachEvent('on' + type, f);
};
}
}();
Source: Javascript Tutorial
It looks like a speed optimization over simply defining the function.
Imagine you had
This is a cross-browser function to add an event that works the same as the example you posted. The difference comes when you have thousands of addEvent calls.
In the example you posted, the function is “simplified” and “materialized” for each browser type at start time (notice the “();” at the end)
you will get either
or
depending on the browser. The choice will never be re-evaluated afterwards (it would be useless since the browser will not change during execution 😉 . Hence the function is avoiding 1 or 2 tests everytime the addEvent function is called ! This can make a difference for such an heavy usage function like addEvent.
I hope this will help you,
Jerome Wagner