我在JavaScript中构建一个纸牌游戏以增加我的web编程排序,并且我遇到了JavaScript Prototype继承的问题。我的设计有一个基卡类,它包含了任何卡所需的所有功能和数据。设计本身是相对灵活的,所以只需通过更改存储的数据大约25%的卡片就可以使用基类。我需要做的是创建新的类,它继承了Card的所有内容(包括数据),但是覆盖可用函数的一小部分而不触及基类功能。JavaScript - 原型继承而不覆盖基类
我一直在尝试使用原型继承来完成这个任务,但是这改变了基类,它不仅使用Card类将任何卡片拧紧,而且还从基类继承其他每个函数。
我需要的是一种设计模式,它允许我只为从卡继承的类重写函数。这是可能的JavaScript?
编辑...
对不起,这里是一个例子,probally应首先增加了这一点。
从基卡类开始。现在
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行为不卡。
我真的在这里面临的问题是卡类有3种方法,我不想在每个子类中定义每个方法。
是的,这是可能的。 – Bergi 2013-02-26 20:20:07
听起来像你想简单的JavaScript继承http://ejohn.org/blog/simple-javascript-inheritance/ – QuentinUK 2013-02-26 20:20:55
@QuentinUK:没有。这不会帮助理解问题。 – Bergi 2013-02-26 20:23:45