0

我正在用 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 种方法,我不想在每个子类中定义每个方法。

4

1 回答 1

8

一个非常简单直接的模式:

function Parent(arg) {
    this.someProperty = arg;
    // initialize all instance properties in the constructor
}


// The prototype should only contain methods and primitive values.
Parent.prototype.someMethod = function() {
    // ...
};

Parent.prototype.someOtherMethod = function() {
    // ...
};


function Child(arg1, arg2) {
    // call parent constructor -- like super() in other languages
    Parent.call(this, arg1);
    // initialize all instance properties in the constructor
}

// Hook up Base.prototype into the prototype chain
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child; // not necessary but can be useful

Child.prototype.someMethod = function() {
   // override method and call parent method
   Base.prototype.someMethod.call(this);
   // ...
};

它依赖于Object.create [MDN]。它创建一个继承自传入对象的新对象。Child.prototype因此,您在and之间获得了一级间接性Parent.prototype,即更改为Child.prototype不影响`Parent.prototype

于 2013-02-26T20:44:20.537 回答