NodeJS 为什么类的示例返回undefined [closed]

cld4siwp  于 2023-04-29  发布在  Node.js
关注(0)|答案(1)|浏览(164)

**关闭。**这个问题是not reproducible or was caused by typos。目前不接受答复。

此问题是由打印错误或无法再重现的问题引起的。虽然类似的问题可能是on-topic在这里,这一个是解决的方式不太可能帮助未来的读者。
5天前关闭。
Improve this question
我用我想要的值初始化目录类的示例,但是当我试图以任何方式操作类的示例时,它返回undefined。

if (beginOfLine == 'dir') {
        let newDirectory = new directory(name); // newDirectory returns undefined
        console.log(name); // returns expected value
        console.log(newDirectory.getDirectoryName()); // returns undefined
        directories.push(newDirectory);
        newDirectory.setParent(currentDirectory);
        currentDirectory.addSubdirectory(newDirectory); 
// throws Cannot read properties of undefined (reading 'push') error 
        currentDirectory = newDirectory;
}

...

module.exports = class directory {

    directory(name) {
        this.name = name;
        this.files = []; 
        this.subdirectories = [];
        this.parent = null;
    }
    

    addSubdirectory(subdirectory) {
        this.subdirectories.push(subdirectory);
    }

    getDirectoryName() {
        return this.name;
    }

    

};
eqqqjvef

eqqqjvef1#

看来你是从java背景。在javascript中,constructor方法不是由class名称定义的。您应该将其定义为constructor

module.exports = class directory {
    constructor(name) {
        this.name = name;
        this.files = []; 
        this.subdirectories = [];
        this.parent = null;
    }

    /**
    Rest of your codes
    **/
}

相关问题