首页 > 解决方案 > 如何使用模块导出直接返回对象?

问题描述

为什么 cat 类不能设置属性,而模块导出是我传递的新对象。

TypeError:无法设置未定义的属性“#sound”

动物类

class Animal
{
    #sound;
    
    // i make it return object this object class.
    setSound(sound)
    {
        this.#sound = sound;

        return this;
    }

    getSound()
    {
        return this.#sound;
    }
}

// i make it create object and return that object.
module.exports = new Animal;

猫类

const {setSound} = require('./animal');

const cat = setSound('Meow');

console.log(cat.getSound());

标签: javascriptnode.js

解决方案


您导出类的实例,因此您不能只从中导入方法。执行以下操作:

const CAT = require('./animal');

const cat = CAT.setSound('Meow');

console.log(cat.getSound());

推荐阅读