【发布时间】:2020-01-18 15:25:48
【问题描述】:
这是我的家庭作业。这是关于建立一个“宇宙模型”,所以没有简单的方法把这个任务放在一个句子里。然而,这是一个需要构造函数、方法和对象的初学者练习。
- 目标:我应该创建一个物质和能量守恒的宇宙表示。
- 基本设置:我应该使用一个名为 Universe 的对象,其中包含两个对象:物质和能量。 (请注意初级)
-
完成的场景/“宇宙”应该如何运作:
- 物质被破坏:宇宙中的能量需要随着物质被破坏的数量而增加
- 物质被创造:宇宙中的能量需要被创造的物质数量减少
- 能量被破坏:宇宙中的物质数量需要随着能量被破坏而增加
- 能量被创造出来:宇宙中的物质数量需要被创造的能量数量所减少
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
这是我的代码,我遇到了语法错误(“{ not expected”)
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
}
}
}
问题是在哪里更正代码以使其运行?请尽量坚持我的知识水平(和尽可能多的示例代码)。
【问题讨论】:
-
你不能像那样在其他人的内部定义成员函数。
-
matter(amount) ... {destroy(amount) {是什么意思? -
@ThisIsNoZaku 我还能如何定义它以便能够像这样调用函数:
Universe.matter.destroy(5) -
先定义一个
matter对象的类?然后,Universe 对象可以将其中一些对象作为成员。 -
@JohnColeman 你的意思是,我将 Universe 设置为普通对象而不是类,而是为物质和能量创建一个类?
标签: javascript object methods constructor