2011-01-05 7 views
1

자바 스크립트/HTML5로 간단한 비디오 게임을 할 때, 한 클래스 내에서 모든 리소스를 수집 할 생각이었습니다 ... 현재 그들은 모든 곳에 퍼져 있습니다.자바 스크립트 클래스 이해 - 리소스 클래스

그래서, 예를 들어, 현재 내가 그러나 그렇게

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"; 
    .. 
    .. 
} 

으로, 나는 하나의 클래스로이 commonize 싶습니다

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"; 
    .. 
    .. 
} 

의 라인을 따라 뭔가를, 나는 돈 이것이 적절한 접근이라고 생각하지 않습니다. 두 번째 구현을 시도 할 때 프로그램이 멋지게 충돌합니다. 리소스로드를 단순화하는 좋은 방법이 있습니까? 당신은 또한 사용할 수

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"; 
    .. 
} 

:

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

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. 
+0

자바 스크립트는 OOP가 아니므로 기존 클래스 모델은 없습니다. 기능은 1 등 시민입니다. – rxgx

답변

1

시도 리터럴 객체를 생성하는 것은 모든 것을 잡아 다음 ...

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

나는 그것을 좋아한다. .. 고마워! – espais

0

이 당신의 이미지 리소스를 넣어 객체를 초기화하십시오 :

관련 문제