Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Superclass Method From Subclass - JavaScript [duplicate]

Possible Duplicate:
set attribute with javascript super method

I am trying to create a simple game in HTML5 for fun. I have an Entity class that is supposed to be the superclass of the Player class.

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;

The problem is at this line:

this.parent.tick.call(this);

I get an error displayed in the JavaScript console of chrome: "Uncaught TypeError: Cannot call method 'call' of undefined".

I don't get it and I've spent a long time trying to find posts of a similar issue. My call to the superclass' constructor works fine but the call to the superclass' tick method does not work.

I'm very new to making games so I have no idea if this a good setup (calling superclass tick from subclass tick). If there is a better, more typical way that people use, please tell.

Thanks.

like image 920
Altherat Avatar asked Dec 07 '12 11:12

Altherat


Video Answer


1 Answers

Adapting this answer to your code:

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;
like image 85
Bergi Avatar answered Oct 12 '22 21:10

Bergi