hi,

i was practising with javascript closure, i tried out one example as
follows

function globalMethod(){
       var num = 200;
       inc = function(){
                num+= 10;
       }
       divBy2 = function(){
              num/=2;
       }

       var alertNum = function(){
                      alert(" THE NUMBER IS "+num);
       }
       return alertNum;
}


var fn26  = function(){
                var ee = globalMethod();
        ee();
        inc();
        ee();
        divBy2();
        ee();
}

window.onload = fn26  ();

this works fine, from above example what i understood is, even if
function "globalMethod" returned closure function which holds the
reference of local variable "num" , the value of num is not lost even
if we manipulate the "num" using functions in global scope as function
"inc()",


now when i tried the next example , it gives a problem, it is as
follows

function buildList(list){
        var arrFun = new Array();
        for(var x = 0; x < list.length; x++){                                   
      arrFun[x] = function()
{ alert(" NUMBER "+list[x]); }
        }
        return arrFun;
}

function fn27(){
        var arr = buildList([23,45,67]);
        for(var x = 0; x < arr.length; x++){
        arr[x]();
        }
}

window.onload = fn27();

here, on page onload there is a three times alert as "NUMBER
undefined",
why so ?
why list[x] is not holding the value which was assigned initially.

waiting for the reply

-- 
To view archived discussions from the original JSMentors Mailman list: 
http://www.mail-archive.com/jsmentors@jsmentors.com/

To search via a non-Google archive, visit here: 
http://www.mail-archive.com/jsmentors@googlegroups.com/

To unsubscribe from this group, send email to
jsmentors+unsubscr...@googlegroups.com

Reply via email to