在这种情况下如何继承对象?

时间:2016-04-06 10:20:40

标签: javascript inheritance

可能已经以某种形式询问了这一点,我尝试检查此资源:https://developer.mozilla.org/en/docs/Web/JavaScript/Inheritance_and_the_prototype_chain

我的gameobject.js看起来像这样:

function GameObject(program)
{
    this.program = program;
    this.graphics = null;
}

GameObject.prototype.update = function(dt)
{

}

GameObject.prototype.draw = function()
{
    // Here graphics would be the graphics of the child class, 
    // because the graphics would be replaced with the child class' graphics
    if(this.graphics !== null)
        this.program.renderer.render(this.graphics);
}

我想要另一个名为box.js的课程:

function Box(program, width, height, x, y)
{
    // Call base constructor here?

    this.width = width;
    this.height = height;
    this.x = x;
    this.y = y;
}

现在我想基本上从GameObject继承更新和绘制方法,并使用program参数调用GameObject构造函数,这样最终该东西应该像这样工作:

var box = new Box(program, 10, 10, 100, 100);

// In game class update method
box.update(this.td);

// In game class draw method
box.draw();

所以基本上就像在C#中完成它一样。如果我能让Box继承更新并从GameObject中绘制方法,那么它已经有了很多帮助。

编辑1:Jsfiddle:https://jsfiddle.net/0df9rfu5/1/

编辑2:我尝试了这样的解决方法:

function Box(program, width, height, x, y)
{
    var self = this;

    this.base = new GameObject(program);

    this.width = width;
    this.height = height;
    this.x = x;
    this.y = y;

    this.update = function(dt) { self.base.update(dt); };
    this.draw = this.base.draw();
}

因此,每次创建Box时,我都会创建一个基类GameObject的新实例,然后将“更新和绘制方法”框设置为GameObject的那些。

虽然这不是诀窍,但我认为这种方法存在任何问题。

编辑3:也许我应该这样做,就像我一直做的那样...从GameObject继承的所有东西仍然必须覆盖更新和绘制方法。只是我想我不能确定gameobject列表中的每个对象都有绘制和更新方法,我只需要假设它们。

1 个答案:

答案 0 :(得分:1)

JavaScript中的构造函数只是普通函数。要从GameObject构造函数中调用Box,您可以使用:

GameObject.call(this, program);

要让Box个对象从GameObject继承,请使用

Object.setPrototypeOf(Box.prototype, GameObject.prototype);

请务必在第一次调用new Box之前将上一行放在上面。

为了与旧浏览器(tank @Bergi)的最佳兼容性,您可以使用新对象覆盖Box.prototype,而不是使用Object.setPrototypeOf

Box.prototype = Object.create(GameObject.prototype, { configurable: true, writable: true, value: Box });

然后,您应该能够在draw个对象上使用updateBox方法。

以下示例可让您走上正确的轨道

function GameObject(program)
{
    this.program = program;
    this.graphics = null;
}

GameObject.prototype.update = function(dt)
{
    alert('updating');
}

GameObject.prototype.draw = function()
{
    // Here graphics would be the graphics of the child class, 
    // because the graphics would be replaced with the child class' graphics
    if(this.graphics !== null)
        this.program.renderer.render(this.graphics);
}

function Box(program, width, height, x, y)
{
    GameObject.call(this, program);

    this.width = width;
    this.height = height;
    this.x = x;
    this.y = y;
}

Object.setPrototypeOf(Box.prototype, GameObject.prototype);

let b = new Box();

b.update();

相关问题