这是我的作业。这是关于建立“宇宙模型”的,所以没有简单的方法可以将这一作业放在一个句子中。但是,这是一个初学者练习,需要构造函数,方法和对象。
4。构建对象时要遵守此要求:
基本物质和能量以负关系相互影响。 -使用上下文实现此对象 -物质和能量对象在称为“宇宙”的对象中定义 -不应在Universe对象之外定义其他变量 -应该有可能对能量或物质给出初始量,否则应默认为0。
5。应该如何工作的示例:
var universe = new Universe(10, 'matter') Universe.matter.total // 10 Universe.energy.total // 0 // or with no initial amount var universe = new Universe() Universe.matter.total // 0 Universe.energy.total // 0 Universe.matter.destroy(5) // 0 Universe.eatter.total // -5 Universe.energy.total // 5 Universe.energy.destroy(-5) // 0 Universe.matter.total // -10 Universe.energy.total // 10 Universe.energy.create(5) // 0 Universe.matter.total // -15 Universe.energy.total // 15
这是我的代码,遇到语法错误(“ {意外”)
class Universe {
constructor (amount, matter = 0, energy = 0) {
this.amount = amount;
this.matter = matter;
this.energy = energy
}
matter(amount) {
destroy(amount) {
this.matter = this.matter - amount;
this.energy = this.energy + amount;
return this.amount
}
create(amount) {
this.matter = this.matter + amount;
this.energy = this.energy - amount;
return this.amount
}
total(amount) {
return this.amount
}
}
energy (amount) {
destroy(amount) {
this.energy = this.energy - amount;
this.matter = this.matter + amount;
return this.amount
}
create(amount) {
this.energy = this.energy + amount;
this.matter = this.matter - amount;
return this.amount
}
total(amount) {
return this.amount
}
}
}
问题是在哪里可以更正代码才能运行?请尝试坚持我的知识水平(并尽可能提供示例代码)。
答案 0 :(得分:1)
Universe类很好,但是如果要使用Matter类型的对象,则还需要创建Matter类。您不能使用自己使用的语法在类本身上定义属性。您需要创建一个单独的类并定义等于该类新实例的属性。
因此,一旦有了Matter类,就可以在Universe类中设置this.matter = new Matter()
,以便可以引用universe.matter
(假设universe
是Universe类的实例,带有类似const universe = new Universe()
的内容