繁体   English   中英

在 javascript 中正确组织类

[英]Proper organize classes in javascript

我在 node.js 中为游戏编写服务器。

我对正确的构造有疑问。 例如我有这个代码:

class mob {
    constructor(name) {
      this.name = name;
      this.health = 100;
    }
    getHealth() {
      return this.health;
    }
}

class items{
    constructor(name, id) {
      this.name = name;
      this.id= id;
      this.value= value;
    }
    getValue() {
      return this.value;
    }
}

 class world {
    constructor(name) {
      this.name = name;
      this.weather = 'rain';
      this.monsters = {};
    }

   addMonster(name) {
     const monster = new mob(name);
     this.monsters['1'] = monster;
   }

   setWeather(weather) {
     this.weather = weather;
   }
   play() {
     this.addMonster('dragon');

   }
 }

game = new world;
game.play();

我想在世界级中操纵天气,而不是在怪物类中使用这样的代码复制它: monster.setWeather('snow');

除此之外,我想在世界类中添加新类,如物品、地图对象等,并使用世界类中的函数来操作它们。 例如: item.setWeather('rainbow'); 并且还操纵其他类上的类,如monster.getItemValue('item')在 javascript 中执行此操作的正确方法是什么?

不知道我理解对不对。

由于您已经有一个全局变量“game”,您可以直接使用“game.setWeather()”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM