Function object constructor

Discussion in 'JavaScript' started by zelenooq, Jan 10, 2009.

  1. #1
    hi
    i saw this function constructor and i dont know what u can get with this function constructor

    can some1 explain that to me what this construct means?
    what is purpose for this type of construct
    thnx
     
    zelenooq, Jan 10, 2009 IP
  2. zelenooq

    zelenooq Peon

    Messages:
    3
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    this what i get somewhere else :)

    ________________________________________________________________

    for example, it can save ram when a bit ends, something like:
    function heavyRamUsage(){
      var ReallyBigFile = 'someFile.txt';
    
      var line94 = (function(file){
        var contents = ajaxText(file);
        var arr = contents.split("\n");
        return arr[93];
      )(ReallyBigFile);
      // do something with line 94 here...
    };
    Code (markup):
    in this way the contents of the text file after it has been loaded, and the extra array we generated is dropped when the function ends, this can be a lot better on ram usage than keeping the huge array around if you are not using it.

    The main usage you will see though, is to pass a reference to something that would normally not be linking there later, for example a number in a loop:
    
    var eles = document.getElementsByTagName('img');
    for(var i = eles.length-1; i >= 0; i--){
      eles[i].onclick = function(){
        alert(i);// doesn't work, I changes on the next loop, so the code doesn't work as we want.
      }
    
      eles[i].onclick = (function(x){
           return function(){
             alert(x);// this does work, since x comes from a function called now.
           };
         }(i);
      }
    }
    Code (markup):
    I hope I haven't confused you here, I'm not very good at explaining things.
     
    zelenooq, Jan 10, 2009 IP
  3. dimitar christoff

    dimitar christoff Active Member

    Messages:
    882
    Likes Received:
    62
    Best Answers:
    0
    Trophy Points:
    90
    #3
    dimitar christoff, Jan 12, 2009 IP