I came across the following pattern when looking through the SlickGrid source code:
(function ($) {
var SlickEditor = {
TextCellEditor: function (args) {
...
},
LongTextCellEditor: function (args) {
...
}
};
$.extend(window, SlickEditor);
})(jQuery);
If I understand this correctly, it is using immediate invocation to define various function objects and then merge them into the global namespace.
So I could just define my functions globally like this and it would have the same effect, right?
function TextCellEditor (args) {
...
}
function LongTextCellEditor (args) {
...
}
The only difference I can see is that in the first version, I can use the $
shorthand to refer to the jQuery
object. Apart from that the result would be identical in both cases.
I would like to know if I am missing something. Maybe there is another good reason for doing things this way?
UPDATE: Please note, I realise that using this immediate invocation pattern allows for the use of private variables declared in the anonymous function. But there aren't any variables declared in this case and the functions are being injected into the global scope anyway. So I'd still like to know if there's any real difference.
Some answers pointed out that referencing local variables is much faster than referencing global variables. Does this still hold true if I reference $
from within the TextCellEditor()
constructor. $
is not really local to TextCellEditor()
since it is defined in the scope of the outer anonymous function.
All comments appreciated.