Calling a superclass method from a subclass - JavaScript

Possible duplicate:
set attribute using javascript super method

I am trying to create a simple game in HTML5 for fun. I have an Entity class, which should be a 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 in this line:

 this.parent.tick.call(this); 

I get an error message displayed in the chrome chrome console: "Uncaught TypeError: cannot call method" call "from undefined".

I do not understand, and for a long time I tried to find messages of a similar problem. My call to the superclass constructor works fine, but the call to the "superclass" method does not work.

I am very new to creating games, so I have no idea if this is a good setting (calling an overclass tick from a subclass). If there is a better, more typical way of using people, please advise.

Thanks.

+7
source share
2 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; 
+7
source

Your question inspired me to look around, and I found what seems to me to be an excellent article by Josh Herzen about this concept.

I am frankly copying some code from my article to set up the extends method for classes:

 function Class() { } Class.prototype.construct = function() {}; Class.extend = function(def) { var classDef = function() { if (arguments[0] !== Class) { this.construct.apply(this, arguments); } }; var proto = new this(Class); var superClass = this.prototype; for (var n in def) { var item = def[n]; if (item instanceof Function) item.$ = superClass; proto[n] = item; } classDef.prototype = proto; classDef.extend = this.extend; return classDef; }; 

After that, your case will be as simple as:

 var Entity = Class.extend({ tick: function() { alert('Entity tick'); } }); var Player = Entity.extend({ tick: function() { alert('Player tick'); arguments.callee.$.tick.call(this); } }); p = new Player(); p.tick(); 

What will warn Player tick , and then Entity tick .

+4
source

All Articles