使用构造函数创建“宇宙”的简单模拟

时间:2019-09-17 18:03:12

标签: javascript object methods constructor

这是我的作业。这是关于建立“宇宙模型”的,所以没有简单的方法可以将这一作业放在一个句子中。但是,这是一个初学者练习,需要构造函数,方法和对象。

  1. 目标:我应该创建一个表示物质和能量守恒的宇宙的表示形式。
  2. 基本设置:我应该使用一个名为Universe的对象,其中包含两个对象:物质和能量。 (请注意初学者级别)
  3. 要实现的场景/“宇宙”应如何发挥作用:
    • 物质被破坏:宇宙中的能量需要被破坏的物质增加
    • 物质被创造:宇宙中的能量需要减少所创造的物质的数量
    • 能量被破坏:宇宙中的物质数量需要通过被破坏的能量来增加
    • 创造了能量:宇宙中的物质需要减少所创造的能量

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
        }
    }
}

问题是在哪里可以更正代码才能运行?请尝试坚持我的知识水平(并尽可能提供示例代码)。

1 个答案:

答案 0 :(得分:1)

Universe类很好,但是如果要使用Matter类型的对象,则还需要创建Matter类。您不能使用自己使用的语法在类本身上定义属性。您需要创建一个单独的类并定义等于该类新实例的属性。

因此,一旦有了Matter类,就可以在Universe类中设置this.matter = new Matter(),以便可以引用universe.matter(假设universe是Universe类的实例,带有类似const universe = new Universe()的内容