2015-02-09 83 views
0

所以我做我的「雪碧」級,而現在它時,它的佈局是這樣工作正常(這是不必要的很多,但可能會幫助你理解):JavaScript - 訂購功能的替代方法?

function Entity(tname) 
    { 
     if (typeof (tname) === 'undefined') tname = "Entity"; 
     this.tname = tname; 
    } 

Entity.prototype.confirmType = function(tname) 
    { 
     if (this.tname === tname) return true; 
     else return false; 
    } 
Entity.prototype.constructor = Entity; 

function Sprite(tname, x, y, src) 
    { 
     this.parent.constructor.call(this, tname); 

     this.x = x; 
     this.y = y; 
     this.img = new Image(); 
     this.img.src = src; 

     this.render = function() 
     { 
      ctx.drawImage(this.img, this.x, this.y); 
     } 
    } 

    Sprite.prototype = Object.create(Entity.prototype); 
    Sprite.prototype.constructor = Sprite; 
    Sprite.prototype.parent = Entity.prototype; 

var sprite = new Sprite("Lucario", 400, 400, "img/slot.png"); 

var update = function() 
{ 
    sprite.render(); 
} 

但我想要什麼要做的就是Spriterender函數就像EntityconfirmType函數,在構造函數之外。

我想要做的是這樣的:

function Sprite(tname, x, y, src) 
    { 
     ... 
    } 

    Sprite.prototype.render = function() 
    { 
     ctx.drawImage(this.img, this.x, this.y); 
    } 

不:

function Sprite(tname, x, y, src) 
    { 
     ... 

     this.render = function() 
     { 
      ctx.drawImage(this.img, this.x, this.y); 
     } 
    } 

基本上,我想要的功能添加到子類,而不只是覆蓋先前存在的。有人能幫我嗎?

+1

這是真的如何縮進你的代碼?只是好奇你爲什麼選擇這種風格? – jfriend00 2015-02-09 00:21:48

+0

不,有些在複製/粘貼過程中遇到了問題。最後一個「var update = function()」就是它通常的樣子。 – 2015-02-09 00:36:53

回答

0

如果我明白你的問題,它可能純粹是你的Javascript語句順序的問題。你不顯示整個代碼序列,但是當你這樣做:

Sprite.prototype = Object.create(Entity.prototype); 

這所以如果你以前把樣機上的任何方法代替Sprite對象的整個原型,他們將被消滅通過這項任務。然後,如果您想更多的方法添加到雪碧的原型,只是將它們添加你這樣做(在此之前)之後:

Sprite.prototype = Object.create(Entity.prototype); 
Sprite.prototype.render = function() { 
    ctx.drawImage(this.img, this.x, this.y); 
} 

如果在其他順序都做了,這是行不通的:

Sprite.prototype.render = function() { 
    ctx.drawImage(this.img, this.x, this.y); 
} 
// replaces the entire prototype object, wiping out any methods that were on it 
Sprite.prototype = Object.create(Entity.prototype); 
+0

謝謝,我試了一下,它的工作!還有另外一個例子,我的答案是正確的,但我仍然不會想到它,因爲我只是一個業餘愛好者...... :( – 2015-02-09 00:32:34