SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Addict tlacaelelrl's Avatar
    Join Date
    Apr 2011
    Location
    Mexico city, Mexico
    Posts
    353
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)

    how to avoid global variables?

    I have a form which the user is able to change the id of, so I have declared an array containing the details of the form and the array is updated in case the details of the form change, so I can have something like

    Code JavaScript:
    formdetails = ['someid', 'index.html', 'post'];

    but the user can change any of those and the form details could be updated to:

    Code JavaScript:
    formdetails = ['someotherid', 'form.php', 'get'];

    then from inside the function I can call the form by doing:

    Code JavaScript:
    document.getElementById(formdetails[0]);

    I am still learning JS and have read a lot that is best to avoid, as much as possible, the usage of global variables and would like to know how I could use that same updated array or any other variable inside a function if is not global
    Do you get bothered because I do the same thing every day?
    Do you question why I do it?
    Then find something that you actually like doing!!!

    Stop thinking on what I do.

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,705
    Mentioned
    102 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by tlacaelelrl View Post
    I am still learning JS and have read a lot that is best to avoid, as much as possible, the usage of global variables and would like to know how I could use that same updated array or any other variable inside a function if is not global
    There are two common techniques that could be applied here.

    Store in the HTML

    The first common technique is to store the information on an HTML element, such as the container within which your script is applied to.

    The benefits of this technique is that you can store any JavaScript variables as properties of the element, and as long as no other scripts try to use the same properties of the same object, you'll be find.

    Here's a simple example to demonstrate that technique.

    Code html4strict:
    <div id="container">
    <p>Content of the container.</p>
    <button id="reveal">Reveal other content</button>
    </div>

    Code javascript:
    document.getElementById('reveal').onclick = function () {
        alert(this.parentNode.otherContent);
    };
     
    var container = document.getElementById('container');
    container.otherContent = 'More content stored as a property of the container.';

    Store in an Object

    The second technique is more complex, where you instantiate a JavaScript object that contains all of your methods, which have access to the variables within the instantiating function.

    The HTML remains the same as above, and here's the JavaScript for that second technique.

    Code javascript:
     
    function someObject(otherContent) {
        function getOtherContent() {
            alert(otherContent);
        }
     
        return {
            getOther: getOtherContent
        };
    }
     
    var myObject = someObject('More content stored as a property of the object.');
     
    document.getElementById('reveal').onclick = myObject.getOther;

    Typically the first technique does fine, and is easier to apply to your code. The second technique is more robust but can be more difficult to understand.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  3. #3
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2006
    Location
    Augusta, Georgia, United States
    Posts
    4,151
    Mentioned
    16 Post(s)
    Tagged
    3 Thread(s)
    I always create separate self calling closures for independent pieces of functionality. Essentially, each closure can be thought of an "individual" module that adds some type of functionality to the application without being reliant (dependent) on anything outside it. This keeps the global namespace just about untouched.

    Code JAVASCRIPT:
    // set-up gallery
    (function() {
     
      	....
     
    })();
     
     
    // Set-up modal window
    (function() {
     
     
    })();
     
     
    // Set-up persistent result page using AJAX
    (function() {
     
     
    })();
     
     
    ...
    The only code I hate more than my own is everyone else's.

  4. #4
    SitePoint Addict tlacaelelrl's Avatar
    Join Date
    Apr 2011
    Location
    Mexico city, Mexico
    Posts
    353
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    is it a good idea to do something like window.myvar = xxx or it would end up the same as declaring a global variable?
    Do you get bothered because I do the same thing every day?
    Do you question why I do it?
    Then find something that you actually like doing!!!

    Stop thinking on what I do.

  5. #5
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,705
    Mentioned
    102 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by tlacaelelrl View Post
    is it a good idea to do something like window.myvar = xxx or it would end up the same as declaring a global variable?
    That is precisely the definition of how to declare a global variable.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •