我正在使用JavaScript構建一個國際象棋遊戲。我正在採取面向對象的方法,並且在處理JavaScript的繼承時遇到一些困難。我想要成爲一個「Piece」抽象類,它包含一些領域和基本的getter/setter,比如這件作品是黑色還是白色。那麼我想爲每種類型片的類,我可以實例像這樣:)如何在JavaScript中擴展一個類
var pieceOne = new Pawn();
典當(應具有的所有字段和計件的方法,但有其自己的運動方法和附加字段(比如它是否已經移動,因爲這對大多數作品都沒有影響)。這是我目前的一塊類:
//This object specifies basic information about pieces.
"use strict";
function Piece(color, type, captured, hasMoved) {
this.color = color;
this.type = type;
this.captured = captured;
this.hasMoved = hasMoved;
this.image = color + "_" + type + ".svg";
}
Piece.prototype.getImage = function getImage(){
return this.image;
}
Piece.prototype.isCaptured = function isCaptured(){
return this.captured;
};
我知道,如果我要做出各種一塊我可能會消除「類型」字段中的一個子類,但是我怎麼能讓一個Pawn子類?像這樣?
function Pawn() = new Piece(color, captured, hasMoved);
Pawn.prototype.getLegalMoves = function getLegalMoves(){
//return legal moves
}
var pieceOne = new Pawn("black", false, false);