Understanding JavaScript classes - resource class

眉间皱痕 提交于 2019-12-24 12:13:54

问题


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


来源:https://stackoverflow.com/questions/4608204/understanding-javascript-classes-resource-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!