Which is best practice, which results in better performance?
UPDATE: jsperf.com reports that (a) is faster @ http://jsperf.com/closure-vs-global-variable
a) using a closure
var obj = {
init: function() {
var self = this;
$('#element').click(function() {
self.clickEvent();
});
},
clickEvent: function() {
this.miscMethod();
},
miscMethod: function() {}
};
b) using the global variable
var obj = {
init: function() {
// removed self=this closure
$('#element').click(this.clickEvent); // simple method handler
},
clickEvent: function() {
obj.miscMethod(); // global variable used
},
miscMethod: function() {}
};
Avoid globals. Global variables and function names are an incredibly bad idea. The reason is that every JavaScript file included in the page runs in the same scope.
Disadvantages of closures There are two main disadvantages of overusing closures: The variables declared inside a closure are not garbage collected. Too many closures can slow down your application. This is actually caused by duplication of code in the memory.
Avoid global variables or minimize the usage of global variables in JavaScript. This is because global variables are easily overwritten by other scripts. Global Variables are not bad and not even a security concern, but it shouldn't overwrite values of another variable.
In JavaScript, closures are the primary mechanism used to enable data privacy. When you use closures for data privacy, the enclosed variables are only in scope within the containing (outer) function. You can't get at the data from an outside scope except through the object's privileged methods.
Both should perform (almost) identically.
Best practice is to avoid globals.
The problem with your closure code is that it won't work in all cases. If you do:
obj.clickEvent()
then it'll work. But if you do:
var f = obj.clickEvent;
//hundreds of lines of code
f();
then it won't, as this
will not refer to obj
on that function call. If you just immediately pass obj
off to something that doesn't use it in a strange way, though, then you won't have that problem, so it's 'cleaner'... but I still think it's too easy to make mistakes, so I recommend the global variable approach.
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