Acoustic77 Acoustic77 - 1 month ago 7
Javascript Question

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

I'm making a file system, but can't figure out how to add a "parent" property.

currently I think my issue is that I can't call a function that hasn't been declared yet, but I don't see how to escape this circular logic then.

the current error is:

Uncaught TypeError: inputDir.getParentDirectory is not a function


and my code is:

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

Answer

You are passing a string to inputDir which causes the error you are seeing since the getParentDirectory() method is defined for file prototype, not string. Instead you need to pass in an instance of file. Another option would be to write code to lookup an instance of file by string.

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

Comments