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) {
   -= nb;

    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);

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

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

let x = .... -=nb;

  let enemies=[];

Then you can subclass

class reallyBadGuys extends Enemies{

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:

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): .

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.
While it does focus on es6 it also details common js implementation and the differences between the two.