【问题标题】:How to make a "getParent" function in a Javascript file directory如何在 Javascript 文件目录中创建“getParent”函数
【发布时间】:2017-03-04 01:49:09
【问题描述】:

我正在制作一个文件系统,但不知道如何添加“父”属性。

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

当前的错误是:

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

【问题讨论】:

  • 此代码有效...是否缺少某些东西?
  • 是的,对不起。我添加了我的第一个声明,即根目录。根的父级显然必须为空,这会导致很多问题。我收到了我在上面发布的那个错误

标签: javascript file tree directory parent


【解决方案1】:

您正在向 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]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-03
    • 1970-01-01
    • 1970-01-01
    • 2011-06-20
    • 2021-06-17
    • 2013-04-15
    • 1970-01-01
    相关资源
    最近更新 更多