Namespace and classes

The question is related to the issue of good practices of organizing a code. I’m making a game and I created a namespace Enemies in which I have some classes like Enemy.. It seemed to me pretty logical to organize it like this but now when I look at it it seems a little weird. I don’t think I’ve seen code like this before. The code works but is it the proper way to write? Plus I see now that I cannot easily extend the prototype of Enemy because I cannot use just Enemy.prototype.someMethod. I’m pasting below a simplified part of my code but it should be enough to see the problem.

"use strict";
var myApp = myApp || {

};

myApp.Enemies = {
    Enemy: function (health, armor) {
        var stats = {
            health: health,
            armor: armor
        };
        this.getHurt = function(nb) {
            stats.health -= nb;
            console.log(stats.health)
        }
    },


    init: function (health, armor, number) {
        var enemies = []
        for (var i = 0; i < number; i++) {
            enemies.push(new this.Enemy(health, armor));
        }
        return enemies;
    }
}

var team1 = myApp.Enemies.init(100, 200, 10);
var team2 =  myApp.Enemies.init(200, 300, 20);
team1[0].getHurt(10);
team2[5].getHurt(50);

Why not use the Class syntax in ES6? Also, use let and const instead of var. Briefly you would write

class Enemies{
   constructor(h,a){
    this.stats={health: h, armor: a};:
  }

getHurt(nb){  
let x = ....
this.stats.health -=nb;
}  

init(h,a,num){
  let enemies=[];
  ...
}

Then you can subclass

class reallyBadGuys extends Enemies{
   constructor(h,a,stuff){
    super(h,a);
.....

This is all syntactic sugar on top of what you wrote, but it really makes things easier. One thing - you might want to use arrow notation for functions, especially callbacks, or you may have to bind this to the functions explicitly. Also, make sure you understand scope in javascript.

Some references:

http://exploringjs.com/es6/index.html#toc_ch_symbols

If you want to see a project which makes extensive use of classes and inheritance, see my Simon Says project (This is not a plug):https://codepen.io/sbrawer/pen/ggWwJJ?editors=0010 .

1 Like

Thank for the answer but I don’t use syntactic sugar on purpose. I want to have in-depth understanding of javascript mechanisms and syntactic sugar hides a lot of what really happens behind the scenes. When I decide that I understand most of mechanisms and patterns I’ll switch to ES6. Shouldn’t be that hard to learn the new syntax while I understand how the language works. Anyway thanks for the resources I’ll get back to them later

I highly recommend you look into module design. Here is resource that helped me. http://exploringjs.com/es6/ch_modules.html
While it does focus on es6 it also details common js implementation and the differences between the two.