我正在用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
这也工作正常。所以我的问题是,在哪种情况下哪种方法更好?两个对象除了具有作为属性的功能以外,还有另一个作为原型的属性之间有什么区别?