2015-02-09 61 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