从子类调用超类方法 - JavaScript

use*_*585 7 javascript inheritance canvas subclass superclass

可能重复:
使用javascript super方法设置属性

我正在尝试用HTML5创建一个简单的游戏以获得乐趣.我有一个Entity类,它应该是Player类的超类.

function Entity(x, y) {

    this.x = x;
    this.y = y;

    this.tick = function() {
        //Do generic stuff
    }
}

function Player(x, y) {

    this.parent.constructor.call(this, x, y);

    this.tick = function() {
        //Do player-specific stuff
        this.parent.tick.call(this);
    }
}

Player.prototype = new Entity();
Player.prototype.constructor = Player;
Player.prototype.parent = Entity.prototype;
Run Code Online (Sandbox Code Playgroud)

问题出在这一行:

this.parent.tick.call(this);
Run Code Online (Sandbox Code Playgroud)

我在chrome的JavaScript控制台中显示错误:"Uncaught TypeError:无法调用未定义的方法'调用'".

我没有得到它,我花了很长时间试图找到类似问题的帖子.我对超类'构造函数的调用工作正常但是对超类'tick方法的调用不起作用.

我对制作游戏非常陌生,所以我不知道这是否是一个好的设置(从子类tick调用超类tick).如果有更好,更典型的方式供人们使用,请告诉我们.

谢谢.

Ber*_*rgi 7

使此答案适应您的代码:

function Entity(x, y) {

    this.x = x;
    this.y = y;

    this.tick = function() {
        //Do generic stuff
    }
}

function Player(x, y) {

    this.parent.constructor.call(this, x, y);

    var oldtick = this.tick;
    this.tick = function() {
        //Do player-specific stuff
        oldtick.call(this);
    }
}

Player.prototype = Object.create(Entity.prototype);
Player.prototype.constructor = Player;
Player.prototype.parent = Entity.prototype;
Run Code Online (Sandbox Code Playgroud)