Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    Regular Coder
    Join Date
    Oct 2002
    Posts
    147
    Thanks
    31
    Thanked 2 Times in 2 Posts

    How do you make a global variable from within a function so every script can use it?

    Hi

    How do I make a variable global so that all other functions can use it.But it is declared inside the function test();

    Thanks


    A


    Code:
    function test(){
    
         var calcAnswer ="hello world";//Can it be done?
    
    }
    
    function answer(){
    
        alert(calcAnswer);
    
    }

  • #2
    Regular Coder
    Join Date
    Mar 2008
    Posts
    301
    Thanks
    2
    Thanked 30 Times in 30 Posts
    WINDOW is the top environment object. Anything listed as a property of WINDOW is considered global.

    You don't use - var - it goes global. It's not a good practice.

    Better to place both inside a function, or self-executing anonymous function. Then declare - var- outside of test()

  • #3
    Regular Coder
    Join Date
    Oct 2002
    Posts
    147
    Thanks
    31
    Thanked 2 Times in 2 Posts
    Hi thanks for the reply

    I don't understand your answer

    can you explain or give an example?

    Thanks

    A

  • #4
    Regular Coder
    Join Date
    Mar 2008
    Posts
    301
    Thanks
    2
    Thanked 30 Times in 30 Posts
    Quote Originally Posted by andrew1234 View Post
    Hi thanks for the reply

    I don't understand your answer
    It's advisable just as a matter of practice to keep variables out of the global namespace. In this browser environment, elements descend from the WINDOW. If you don't use - var - your name and primitive, calcAnswer, will be a property of WINDOW. If you DON'T use - var.

    However, if you wanted to make calcAnswer available to different functions, and instead of making it a property of an object you just wanted the name out there, globally, you could hide it from WINDOW by a) using var as you do, b) declaring it outside test(), but c) putting calcAnswer, test() and the other inside yet another function. That function and the - var- will hide it from WINDOW. Your 'calcAnswer' would not be enumerated as a property of WINDOW if you listed it out using for-in. But it would be available to all the inner functions.

    That will be so obvious to people who post here, but you CAN place functions inside of functions, in Javascript. Much of what is now done in Javascript pretty much depends on this capability.

  • Users who have thanked fside for this post:

    andrew1234 (07-19-2009)


  •  

    Posting Permissions

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