Javascript Closure Question

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • dhsieh
    New Member
    • Aug 2007
    • 13

    Javascript Closure Question

    Hello all,

    I have been trying to understand how JavaScript closures work but I have been struggling. In this code snippet that I created to test things, I can't figure out how to change the value of the variable a to "b" without passing an argument into the function or returning the value. Can someone please help? Also, does anyone know of a site that explains closures in simple detail? Thanks.

    Code:
    function a() {
    	var a = "a";
    	blah = function() {
    		a = "b";
    	}
    	alert(a);
    }
  • dmjpro
    Top Contributor
    • Jan 2007
    • 2476

    #2
    Originally posted by dhsieh
    Hello all,

    I have been trying to understand how JavaScript closures work but I have been struggling. In this code snippet that I created to test things, I can't figure out how to change the value of the variable a to "b" without passing an argument into the function or returning the value. Can someone please help? Also, does anyone know of a site that explains closures in simple detail? Thanks.

    Code:
    function a() {
    	var a = "a";
    	blah = function() {
    		a = "b";
    	}
    	alert(a);
    }
    Look ...... two name coincides "function a" and "var a".
    The main problem is not here.
    Actually you can't change local references inside Closures :)
    You have to declare it as "Global".

    Debasis Jana

    Comment

    • dhsieh
      New Member
      • Aug 2007
      • 13

      #3
      So this would effectively change the value of a to "b" globally?

      Code:
      var a = "a";
      function test() {
          blah = function() {
              a = "b";
          }
          alert(a);
      }

      Comment

      • dmjpro
        Top Contributor
        • Jan 2007
        • 2476

        #4
        Originally posted by dhsieh
        So this would effectively change the value of a to "b" globally?

        Code:
        var a = "a";
        function test() {
            blah = function() {
                a = "b";
            }
            alert(a);
        }
        Call the function then see what happens.
        [code=javascript]
        alert(a);
        blah();
        alert(a)
        [/code]

        Debasis Jana

        Comment

        Working...