Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript closure vs. global variable

Tags:

javascript

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() {}
};
like image 268
Matty F Avatar asked Nov 03 '10 02:11

Matty F


People also ask

Is it bad to use global variables in JavaScript?

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.

What are the disadvantages of closures in JavaScript?

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.

Why should we avoid global variables in JavaScript?

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.

Why would you use a closure in JavaScript?

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.


2 Answers

Both should perform (almost) identically.

Best practice is to avoid globals.

like image 172
SLaks Avatar answered Sep 29 '22 15:09

SLaks


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.

like image 40
Claudiu Avatar answered Sep 29 '22 14:09

Claudiu