2012-12-27 4 views
1

개체 변수를 식별하지만 나는 내 개체의 OOP에 갇히지 아니에요. 개체의 함수 내부에서 개체의 변수를 참조하는 데 문제가 있습니다.내가 소켓을 사용하여 자바 스크립트 게임을 만들기 위해 노력하고

여기에 몇 가지 문제가있을 수 있습니다. 렌더링 함수가 아니라 객체 내에서 draw 함수를 호출합니다. 또한 개체 리터럴 디자인이 올바르게 수행되었는지 확실하지 않습니다. Require.js 및 class.js를 사용

, 우리의 user.js 있습니다

define(['entity'],function(Entity){ 
var User = Entity.extend({ 
    init: function(){ 
     this.health= 10; 

    }, 

    draw: function(ctx){ 
     img = new Image(); // Create new img element 
     img.onload = function(){ 
     // execute drawImage statements here 
     ctx.drawImage(img, this.posx, this.posy); 
     }; 
     img.src = '/images/object.PNG'; // Set source path 
    } 
}) 
return User;}) 

define(function(){ 
var Entity= Class.extend({ 
    init: function(){ 
     //object image 
     this.img.src = '/images/Blue-soldier.PNG'; 
     //location 
     this.posx=50; 
     this.posy=50; 
     //gameplay values 
     this.health=1; 
     this.speed=0; 

    }, 

User.draw (CTX)를 game.js에라고

Entity.js에서 연장 :

var entity = new User; 
    this.users.push(entityid); 
    entity.draw(ctx); 
}, 

this.posx 및 this.posy는 user.draw()에 인식되지 않습니다. 하드 값으로 바뀌면 잘 작동합니다. 나는 무엇을 놓치고 있습니까?

내 전체 코드는 좀 더 복잡하지만, 당신은 https://github.com/mtbarta/canvas/blob/master/public/javascripts/client.js

감사에서 그것을 찾을 수 있습니다!

+0

당신은 var''와 지역 변수 "IMG"를 선언해야! – Pointy

답변

1

문제는 "load"핸들러에서 this을 사용하려고하는 것입니다. 여기서 값은 "draw"함수의 값이 아닙니다. 이 시도 :

var entity = this; 
    img.onload = function(){ 
     // execute drawImage statements here 
     ctx.drawImage(img, entity.posx, entity.posy); 
    }; 

지역 변수 "법인"에 this의 사본을 보존함으로써, 핸들러가에 액세스 할 수 있습니다.

관련 문제