如何在 Javascript 文件目录中创建 "getParent" 函数

How to make a "getParent" function in a Javascript file directory

我正在制作文件系统,但不知道如何添加 "parent" 属性。

目前我认为我的问题是我无法调用尚未声明的函数,但我不知道如何逃避这种循环逻辑。

当前错误是:

Uncaught TypeError: inputDir.getParentDirectory is not a function

我的代码是:

var file = function(FileName,inputDir,isDir){
this.Name=FileName;
this.CurrentDir=inputDir;
this.isDirectory = isDir;
this.size = 0;
this.timeStamp = new Date();
if(isDir===true){
    this.subfiles = [];
}
if(inputDir!==null){
    this.parentDir = inputDir.getParentDirectory();
}
this.rename = function(newName){
    this.Name = newName;
};
this.updateTimeStamp = function(){
    this.timeStamp = new Date();
};  
};

file.prototype.getParentDirectory = function(){
        return this.parentDir;
    };

var fileSystem = function(){
    this.root = new file("root",null,true);
    this.createFile = function(name,currentDirectory,isDirectory){
        var f = new file(name,currentDirectory,isDirectory);
        currentDirectory.subfiles.push(f);
    };
};

var myComputer = new fileSystem();
myComputer.createFile("Desktop","root",true);

您正在将字符串传递给 inputDir,这会导致您看到错误,因为 getParentDirectory() 方法是为文件原型而不是字符串定义的。相反,您需要传入一个文件实例。另一种选择是编写代码以按字符串查找文件实例。

var file = function(FileName,inputDir,isDir){
this.Name=FileName;
this.CurrentDir=inputDir;
this.isDirectory = isDir;
this.size = 0;
this.timeStamp = new Date();
if(isDir===true){
    this.subfiles = [];
}
if(inputDir!==null){
    this.parentDir = inputDir.getParentDirectory();
}
this.rename = function(newName){
    this.Name = newName;
};
this.updateTimeStamp = function(){
    this.timeStamp = new Date();
};  
};

file.prototype.getParentDirectory = function(){
        return this.parentDir;
    };

var fileSystem = function(){
    this.root = new file("root",null,true);
    this.createFile = function(name,currentDirectory,isDirectory){
        var f = new file(name,currentDirectory,isDirectory);
        currentDirectory.subfiles.push(f);
    };
};

var myComputer = new fileSystem();
myComputer.createFile("Desktop",myComputer.root,true);
console.log("myComputer:", myComputer);
console.log("Desktop:", myComputer.root.subfiles[0]);