简体   繁体   English

引用自身的javascript函数

[英]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. 我想知道当函数引用自身(例如以下函数)时在javascript中称为什么。

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. v变量是原始文件,“文件夹”对象只是文件夹/文件的列表/数组。

I'm wondering, how to keep the original v variable? 我想知道,如何保留原始v变量? 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();
}

You can use a closure to capture v : 您可以使用闭包捕获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);
}

Solution 1: you can send in two parameters original_v and v. Where original_v doesn't change and v changes. 解决方案1:您可以输入两个参数original_v和v。其中original_v不变且v改变。 In recursive methods it's pretty normal to do this. 在递归方法中,这样做是很正常的。

Solution 2: Make a wrapper clojure/function.. Something like this 解决方案2:制作包装Clojure /函数。像这样

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();    
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM