I’m building a card game in JavaScript in order to increase my web programming chops, and I’m having an issue with JavaScript Prototype inheritance. My design has a base Card class that contains all of the function and data any card will ever need. The design itself is relatively flexible, so just by changing the data stored about 25% of cards can use the base class. What I need to do is create new classes that inherits everything from Card – including the data – but overrides a small subset of the available functions without touching the base class functions.
I’ve been attempting to use prototype inheritance to accomplish this, but this changes the base class, which not only screws up any cards using the Card class, but also every other function that inherits from the base class.
What I need is a design pattern that allows me to override a function ONLY for the classes inheriting from Card. Is this possible in JavaScript?
Edit...
Sorry, here's an example, probally should have added this in the first place.
Starting with the Base Card class.
function Card(){
this.cardID = 0;
this.name = '';
this.imageID = 0;
this.imageURL = '';
this.imageAlt = '';
etc....
}
Card.prototype.init = function( inID
, inName
, inImageID
, inImageURL
, inImageAlt
, inImageHorizontal
etc...
){
this.cardID = inID;
this.name = inName;
this.imageID = inImageID;
this.imageURL = inImageURL;
this.imageAlt = inImageAlt;
}
Card.prototype.whenPlayed = function(){
return false;
}
Now my Child Class:
ChildCard.prototype = new Card();
ChildCard.constructor = ChildCard;
function ChildCard(){};
ChildCard.prototype.whenPlayed = function(){
alert("You Win!");
return true;
}
As it stands now if I were to create a Card object and call its whenPlayed I'd get the behavior from ChildCard not Card.
The issue I'm really facing here is the card class has approaching 3 donzen methods, and I don't want to have to define each one in each child class.