0

Web プログラミングのスキルを高めるために JavaScript でカード ゲームを作成していますが、JavaScript プロトタイプの継承に問題があります。私のデザインには、すべてのカードが必要とするすべての機能とデータを含む基本 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 を呼び出すと、Card ではなく ChildCard から動作が取得されます。

ここで私が実際に直面している問題は、カード クラスに 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したがって、との間で 1 レベルの間接性が得られます。Parent.prototypeつまり、変更は にChild.prototype影響を与えません`Parent.prototype

于 2013-02-26T20:44:20.537 に答える