我正在用 JavaScript 构建一个纸牌游戏,以增加我的网络编程能力,但我遇到了 JavaScript Prototype 继承问题。我的设计有一个基础 Card 类,其中包含任何卡片所需的所有功能和数据。设计本身比较灵活,因此只需更改存储的数据,大约 25% 的卡片可以使用基类。我需要做的是创建新类,它继承 Card 的所有内容(包括数据),但在不触及基类函数的情况下覆盖一小部分可用函数。
我一直在尝试使用原型继承来实现这一点,但这会改变基类,这不仅会破坏使用 Card 类的任何卡片,还会破坏从基类继承的所有其他函数。
我需要的是一种设计模式,它允许我只为从 Card 继承的类覆盖一个函数。这在 JavaScript 中可能吗?
编辑...
对不起,这是一个例子,可能应该首先添加这个。
从基卡类开始。
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;
}
现在我的孩子班:
ChildCard.prototype = new Card();
ChildCard.constructor = ChildCard;
function ChildCard(){};
ChildCard.prototype.whenPlayed = function(){
alert("You Win!");
return true;
}
就目前而言,如果我要创建一个 Card 对象并调用它 whenPlayed,我会从 ChildCard 而不是 Card 获得行为。
我在这里真正面临的问题是卡片类有接近 3 种方法,我不想在每个子类中定义每个方法。