我正在用javascript構建一個國際象棋遊戲,並且對使用繼承的正確方法有點不確定。在代碼中的一個部分,我有不同的片類型的擴展它,例如與騎士一塊對象(因爲它是最短的),它看起來像這樣(沒有評論):在JavaScript中,我應該添加函數到對象還是對象原型
件
/************* piece ********************/
function Piece(square, color) {
this.square = square;
this.color = color;
}
Piece.prototype.get_path = function(to) {
return null;
};
Piece.prototype.get_capture_path = function(to) {
return this.get_path(to);
};
Piece.prototype.isAt= function(square) {
return (this.square.equals(square));
};
/************* KNIGHT *****************/
Knight.prototype = Object.create(Piece.prototype);
Knight.prototype.constructor = Knight;
function Knight(square, color) {
Piece.call(this, square, color);
this.type = KNIGHT;
}
Knight.prototype.get_path = function(to) {
var h_movement = Math.abs(this.square.file - to.file);
var v_movement = Math.abs(this.square.rank - to.rank);
if ((h_movement === 2 && v_movement === 1) || (h_movement === 1 && v_movement === 2)) {
return [to];
}
return null;
};
,它工作正常,如你所期望的物體看起來根據Chrome的輸出的console.log如下:在代碼中的不同的文件
Knight {square: Square, color: "w", type: "N"}
color: "w"
square: Square
type: "N"
__proto__: Knight
constructor: Knight(square, color)
get_path: (to)
__proto__: Piece
現在,我有一個方形物體的定義,哪個廁所KS這樣的:
廣場
function Square(file, rank) {
this.file = file;
this.rank = rank;
this.equals = function(other) {
return (this.file === other.file && this.rank === other.rank);
};
this.toString = function() {
return String(file) + ' ' + String(rank);
};
this.getSquareAtOffset = function(file, rank) {
file = Number(file)? file : 0;
rank = Number(rank)? rank : 0;
return new Square(this.file + file, this.rank + rank);
}
};
這也工作得很好,而且,你可能會想到,對象的控制檯日誌如下:
Square {file: 1, rank: 1}
equals: (other)
file: 1
getSquareAtOffset: (file, rank)
rank: 1
toString:()
__proto__: Square
這也工作正常。所以我的問題是,在哪種情況下哪種方法更好?兩個對象除了具有作爲屬性的功能以外,還有另一個作爲原型的屬性之間有什麼區別?