0

I have a simple function which changes a variable passed to it. But after exiting the function, the variable return to it old value. I don't know why or how to fix it

<!DOCTYPE html>
<html>
<head>

  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>    

  <script>
    $(document).ready(function() {
        var a='test';

        $().doit(a);
        alert(a);
    });

    (function ($) {
            $.fn.doit = function (input) {
                alert(input);
                input='new';
                alert(input);
            };

    }(jQuery));
  </script>
</head>

<body>
</body>
</html>
user2174870
  • 247
  • 2
  • 11
  • read http://stackoverflow.com/questions/2835070/is-there-thing-like-pass-by-value-pass-by-reference-in-javascript and http://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language – Arun P Johny May 30 '13 at 08:08

2 Answers2

4

This is by design, when the variable exits the inner scope (your doit function) the value goes back to the previous value, because in JS the variables are always passed by value.

If you vant to keep the value you have to return the value from your function:

<script>

    $(document).ready(function() {
        var a='test';

        a = $().doit(a);
        alert(a);
    });

    (function ($) {
            $.fn.doit = function (input) {
                alert(input);
                input='new';
                alert(input);
                return input;
            };

    }(jQuery));
  </script>

You can see it working here: http://jsfiddle.net/nQSNy/

DocKuro
  • 445
  • 4
  • 13
1

It's because you are passing the variable a by value and not by reference. You could however return a value from your function and use that.

chead23
  • 1,859
  • 11
  • 12