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.
The difference is that you are creating a local scope for private variables when you use a self invoking function like the one you have shown.
That type of self invoking function is usually called a closure and is the basis of many javascript patterns like the module pattern: http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth
You can read more about javascript scoping here: http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting
The reason for passing the jQuery vairable in is 2 fold:
1: it's more convinient to call it via $ and since it was passed in as a local variable we can be sure that $ isn't something else
2: it's faster - local variables are much faster to access and work with than global variables
As an example take a look at the following chunk of code:
var public_and_global=true;
(function(){
var private_and_local = true;
function local_func() {
//can use private_and_local as well as public_and_global
}
})();
function global_func() {
//can only use public_and_global
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With