2012-12-27 68 views
1

我想創建一個使用套接字的JavaScript遊戲,但我被困在我的對象的OOP。我在引用對象函數內的對象變量時遇到了問題。對象文字JavaScript模式不能識別對象變量

這裏可能有幾個問題。我從對象中調用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;}) 

從Entity.js延伸

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 :

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

問題是,您正試圖在「加載」處理程序中使用this,其中值不會是「draw」函數中的值。試試這個:

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

通過在局部變量「實體」保留的this副本,該處理器將有機會獲得它。