首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用构造函数创建“宇宙”的简单模拟

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

Stack Overflow用户
提问于 2019-09-17 18:03:12
回答 1查看 72关注 0票数 0

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

  1. Goal: I应该创建一个宇宙的表示,在那里物质和能量是守恒的。
  2. Basic安装程序:I应该使用一个名为Universe的对象,其中包含两个对象:物质和能量。(请注意初学者level)
  3. Scenarios来完成/如何完成“宇宙”应该如何运作:宇宙中的物质被破坏了:宇宙中的能量需要被物质的数量增加,destroyed
  4. Matter被创造出来;宇宙中的能量需要被物质的数量减少,created
  5. Energy被破坏的数量;宇宙中的物质的数量需要随着能量的产生而增加:宇宙中的物质数量需要被能量created

的数量减少:宇宙中的物质数量需要被能量created的数量减少。

4.在构建对象时尊重这一点:

基本上,物质和能量在一种负关系中相互影响。-使用上下文实现这个对象--物质和能量对象是在一个称为宇宙的对象中定义的--不应该在宇宙对象之外定义其他变量--应该可以给出能量或物质的初始值,否则应该默认为0。

5.它应该如何工作的示例:

变量宇宙=新宇宙(“物质”) Universe.matter.total // 10 Universe.energy.total // 0/或无初始量变量宇宙=新宇宙() 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

这是我的代码,我遇到了一个语法错误("{非预期的“)

代码语言:javascript
复制
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
        }
    }
}

问题是在哪里纠正代码,以便它运行?请尽量坚持我的知识水平(尽可能多地使用示例代码)。。

EN

回答 1

Stack Overflow用户

发布于 2019-09-17 18:24:21

Universe类是可以的,但是如果您希望对象具有Matter类型,则还需要创建一个Matter类。不能用所使用的语法来定义类本身的属性;您需要创建一个单独的类,并定义与该类的新实例相等的属性。

因此,一旦您有了一个Matter类,就可以在Universe类中设置this.matter = new Matter(),以便您可以引用universe.matter (假设universe是由类似于const universe = new Universe()的东西创建的Universe类的一个实例)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57979753

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档