gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 05:50:20 29 4
gpt4 key购买 nike

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

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

当前错误是:

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() 方法是为文件原型(prototype)而不是字符串定义的。相反,您需要传入一个文件实例。另一种选择是编写代码来通过字符串查找文件实例。

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

关于javascript - 如何在Javascript文件目录中创建 "getParent"函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40181910/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com