Ke.
Ke.

Reputation: 2586

javascript function that refers to itself

I'm wondering what it is called in javascript, when a function refers to itself such as the following function.

This function is being used to recursively navigate through folders on a hard drive. The v variable is the original file and the "Folder" object is just a list/array of folders/files.

I'm wondering, how to keep the original v variable? It keeps changing whenever the function is run (on itself), so I can't access the original variable that started the function.

function recursefolders(v){
    var f = new Folder(v);
    while (!f.end) {
        if (f.filetype == "fold") {
            var foldername;
            foldername =  f.pathname + f.filename
            recursefolders(foldername);
alert('This is the original variable' + v);

        }
        f.next();
    }   
    f.close();
}

Upvotes: 0

Views: 58

Answers (2)

Stian Standahl
Stian Standahl

Reputation: 2619

Solution 1: you can send in two parameters original_v and v. Where original_v doesn't change and v changes. In recursive methods it's pretty normal to do this.

Solution 2: Make a wrapper clojure/function.. Something like this

function recursefolders(v){
    var original_v = v;
    recurseSubfolders(original_v);
    function recurseSubfolders(v){
        while (!f.end) {
            if (f.filetype == "fold") {
                var foldername;
                foldername =  f.pathname + f.filename
                recurseSubfolders(foldername);
                alert('This is the original variable' + original_v);
            }

            f.next();
        }   

        f.close();    
    }
}

Upvotes: 0

haim770
haim770

Reputation: 49095

You can use a closure to capture v:

function recursefolders(v) {
  var capturedV = v;

  function folderTraversal(v) {
    var f = new Folder(v);
    while (!f.end) {
      if (f.filetype == "fold") {
        var foldername;
        foldername = f.pathname + f.filename
        folderTraversal(foldername);
        alert('This is the original variable' + capturedV);
      }
      f.next();
    }
    f.close();
  }

  folderTraversal(v);
}

Upvotes: 1

Related Questions