SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Zealot Bruce Lee's Avatar
    Join Date
    Jan 2005
    Location
    Singapore
    Posts
    198
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    how to declare public variables?

    how to declare a variable which i can use in another function.

    function1()
    {
    var x;
    }

    i need to use "x" variable in another function asy function2

    function2()
    {
    alert (x);
    }
    Happy Coding!!!
    Bruce Lee.

  2. #2
    SitePoint Zealot
    Join Date
    Jun 2004
    Location
    Kansas City, MO
    Posts
    143
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Declare it outside the function.

  3. #3
    Tranceoholic lilleman's Avatar
    Join Date
    Feb 2004
    Location
    Írebro, Sweden
    Posts
    2,716
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi,

    It will also become global if you omit the var keyword.
    ERIK RIKLUND :: Yes, I've been gone quite a while.

  4. #4
    SitePoint Wizard
    Join Date
    Mar 2001
    Posts
    3,537
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    In addition, you can use the window object's array notation: window["var_name"]. Summing up:

    1)Declared outside any function:
    Code:
    var x = "hello";
    
    function f1()
    {
    	alert(x);
    }
    
    function f2()
    {
    	alert (x);
    }
    
    f1();
    f2();
    2)Inside the function without the var keyword:
    Code:
    function f1()
    {
    	x= "hello"
    	alert(x);
    }
    
    function f2()
    {
    	alert (x);
    }
    
    f1();
    f2();
    3)Using the window object:
    Code:
    function f1()
    {
    	window["x"] = "hello"
    	alert(x);
    }
    
    function f2()
    {
    	alert (x);
    }
    
    f1();
    f2();
    In my opinion, 1 and 3 are preferable.

  5. #5
    SitePoint Wizard stereofrog's Avatar
    Join Date
    Apr 2004
    Location
    germany
    Posts
    4,324
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    For the sake of completeness, you can also use "static member" notation.

    Code:
    function a () {
    	a.x = 10;
    }
    function b() {
    	alert(a.x)
    }
    a()
    b()
    "window" is not that good because less portable.


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
  •