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
    New to the CF scene
    Join Date
    Apr 2012
    Posts
    9
    Thanks
    8
    Thanked 1 Time in 1 Post

    Javascript - Access a Global Variable from inside a function

    Hi,

    Is is possible to access a global variable for use inside a function?

    Thanks for help in advance

    Mike

  • #2
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    3,020
    Thanks
    56
    Thanked 566 Times in 563 Posts
    Mike,

    you need to either:
    a) post this question in a branch that is designated for questions (this one is for showcasing "finished" javascripts)
    or
    b) test it yourself

    I recommend b as being the speedier and more satisfying course of action

  • Users who have thanked xelawho for this post:

    PioStudios (05-19-2012)

  • #3
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Well someone has moved the question to the right forum so it is only reasonable to answer it.

    Three examples for you:

    Code:
    var a = 1;
    b = function() {
    var c = 2;
    a = c;
    }
    In this example because the function b() has no local variable a the reference to that variable inside the function is taken to refer to the global variable.


    Code:
    var a = 1;
    b = function() {
    var a = 3, c = 2;
    a = c;
    }
    In this version function b() does have its own ;ocal variable a and so the references within the function are to the local a and not to the global a. To reference the global variable we can change that code to:

    Code:
    var a = 1;
    b = function() {
    var a = 3, c = 2;
    window.a = c;
    }
    The window.a reference is to the global variable a and not to the local variable a.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • Users who have thanked felgall for this post:

    PioStudios (05-19-2012)

  • #4
    New to the CF scene
    Join Date
    Apr 2012
    Posts
    9
    Thanks
    8
    Thanked 1 Time in 1 Post
    Sorry for posting in the wrong forum. Genuine mistake.

    @felgall - sincere thanks for your answer. It is excellent. Thanks for taking the time to explain it. Appreciate it.


  •  

    Posting Permissions

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