Friday, September 27, 2013

Better Global variables in Javascript

If you are using variables in Javascript in the traditional way as follows:

    var testVariable = 1;
    function foo(){

Then you may be wrong, because this case may fail when you integrate many Javascript files into one. I found that there's a workaround to fix this problem by attaching the variable to a window object. Here's how it can be done:

    var window.testVariable = 1;
    function foo(){

I find that this is a wonderful way to avoid a lot of problems and confusions regarding global variables in Javascript.

No comments:

Post a Comment