Javascript - 订购功能的替代方式?

时间:2015-02-09 00:16:39

标签: javascript function class prototype

所以我正在制作我的“Sprite”课程,现在它正常工作,如此布局(很多都是不必要的,但可能有助于你理解):

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();
}

但我想要做的是在构造函数之外使Sprite的{​​{1}}函数与render的{​​{1}}函数一样。

我想做的是:

Entity

confirmType

基本上,我想向子类添加函数,而不是仅仅覆盖预先存在的函数。有人能帮助我吗?

1 个答案:

答案 0 :(得分:0)

如果我理解您的问题,可能纯粹是您的Javascript语句顺序的问题。您没有显示整个代码序列,但是当您执行此操作时:

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

它取代了Sprite对象上的整个原型,所以如果你以前在原型上放了任何方法,它们将被这个赋值消灭掉。如果您想要为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);