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

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

本文关键字:quot getParent 函数 文件目录 Javascript 一个 何创建 创建      更新时间:2023-09-26

我正在创建一个文件系统,但是不知道如何添加一个"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()方法是为文件原型定义的,而不是字符串。相反,您需要传入一个file的实例。另一种选择是编写代码按字符串查找file的实例。

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]);