Javascript variable declaration & scope
    <html>
    <head>
    <script type='text/javascript'>
        var process = function (test) {
          var i = test;
          this.echo = function () { console.log(i); };
        };
        var test = 'hai';
        var hai = new process(test);
        hai.echo();
        test = 'sorry';
        hai.echo();
    </script>
    </head>
    <body style='height:1000px;width:100%'>
    </body>    

On executing the above test script I'm getting 'sorry' twice which I expected to be 'hai' then 'hai'. 

When I change line 5 as [gave a random try]

    var i = (function () {return test;})();

I got it 'hai' & 'hai'

How does it work in the case 2 & why didn't it in case 1? 

AFAI, javascript does variable hoisting and because of that *test* will be initialized to *undefined* in the beginning of scope and will be reassigned as and when it is assigned with the values. But here that didn't help me out. 
Javascript variable declaration & scope
===

    <html>
    <head>
    <script type='text/javascript'>
        var process = function (test) {
          var i = test;
          this.echo = function () { console.log(i); };
        };
        var test = 'hai';
        var hai = new process(test);
        hai.echo();
        test = 'sorry';
        hai.echo();
    </script>
    </head>
    <body style='height:1000px;width:100%'>
    </body>    

On executing the above test script I'm getting 'sorry' twice which I expected to be 'hai' then 'hai'. 

When I change line 5 as [gave a random try]

    var i = (function () {return test;})();

I got it 'hai' & 'hai'

How does it work in the case 2 & why didn't it in case 1? 

AFAI, javascript does variable hoisting and because of that *test* will be initialized to *undefined* in the beginning of scope and will be reassigned as and when it is assigned with the values. But here that didn't help me out. 