Understanding JavaScript classes - resource class

2019-07-26 22:25发布

问题:

Working on a simple video game in JavaScript / HTML5, and I had a thought to collect all of my resources within one class...currently they're spread all over the place.

So, for an example, currently I have something along the lines of

function c_enemy_sprites() {
  this.image = new Image();
  this.image.src = "res/enemies.png";
  ..
  ..
}

function c_tilemap() {
  this.image = new Image();
  this.image.src = "res/tilemap.png";
  ..
  ..
}

I'd like to commonize this into a single class, as so

function c_resource() {
  this.enemies.image = new Image();
  this.enemies.image.src = "res/enemies.png";

  this.tilemap.image = new Image();
  this.tilemap.image.src = "res/tilemap.png";
  ..
  ..
}

However, I don't think this is the proper approach. The program crashes spectacularly when I try the second implementation. Is there a good way to simplify my resource loading?

回答1:

Try creating an object literal to hold everything:

function C_resource(src) {
    this.image = new Image();
    this.image.src = src;
}

var resources = {
    enemies : new C_resource('res/enemies.png'),
    tilemap : new C_resource('res/tilemap.png')
};

resources.enemies.image; // your enemies image.


回答2:

Try initializing an object to put your image resource in:

function c_resource() {
  this.enemies = {};
  this.enemies.image = new Image();
  this.enemies.image.src = "res/enemies.png";
  this.tilemap = {};
  this.tilemap.image = new Image();
  this.tilemap.image.src = "res/tilemap.png";
  ..
}

You also could use:

function Resource(path){
   this.image = new Image();
   this.image.src = path;
   ... further initialization, etc.
}

then...

function resources(){
  this.enemies = new Resource('res/enemies.png');
  this.tilemap = new Resource('res/tilemap.png');
}