javascript - 如何使用模块导出直接返回对象?
问题描述
为什么 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());
解决方案
您导出类的实例,因此您不能只从中导入方法。执行以下操作:
const CAT = require('./animal');
const cat = CAT.setSound('Meow');
console.log(cat.getSound());
推荐阅读
- java - Java:有没有转换ArrayList的方法
到 boolean[] (原始数组)? - flutter - Flutter,第二个动画控制器没有动画,为什么?
- c# - 使用相同库 api 的 Rabbitmq 的性能非常不同(python3 与 dotnet)
- perl - 在perl中没有数组的情况下以相反的顺序搜索段落
- regex - 如何使用 PowerShell 实例化对象并设置成员字段?
- java - 点燃缓存事务强制回滚
- python - 将多列拆分为新行
- angular - 从 V8 更新到 V9 后,Angular App 无法编译
- javascript - React JS - 使用自定义方法获取
- swift - 第二次函数调用后才可用的值