了解JavaScript类-资源类 [英] Understanding JavaScript classes - resource class
本文介绍了了解JavaScript类-资源类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用JavaScript/HTML5开发一个简单的视频游戏,我想到了将我所有的资源收集到一个类中的方法……目前,这些资源分布在整个地方.
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?
推荐答案
尝试创建一个对象常量以容纳所有内容:
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.
这篇关于了解JavaScript类-资源类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文