在javascript中,我应该向对象或对象原型添加函数

Nes*_*cio 5 javascript oop javascript-objects

我正在用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;
};
Run Code Online (Sandbox Code Playgroud)

并且它工作正常,正如您所期望的那样,根据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
Run Code Online (Sandbox Code Playgroud)

现在在代码的不同文件中,我有一个方形对象的定义,如下所示:

广场

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);
    }
};
Run Code Online (Sandbox Code Playgroud)

这也很好,并且,正如您可能期望的那样,对象的控制台日志如下:

Square {file: 1, rank: 1}
equals: (other)
file: 1
getSquareAtOffset: (file, rank)
rank: 1
toString: ()
__proto__: Square
Run Code Online (Sandbox Code Playgroud)

这也很好.所以我的问题是,在哪种情况下哪种方法更好?两个对象之间有什么区别,除了一个具有它作为属性的功能而另一个具有它作为原型的属性?

aug*_*uag 3

实际首选或推荐的编写方式是作为对象:

var Square = {};
Square.file = file;
Square.rank = rank;
Square.equals = function(other) {
   return (this.file === other.file && this.rank === other.rank);
};
Square.toString = function() {
    return String(file) + ' ' + String(rank);
};
Square.getSquareAtOffset = function(file, rank) {
    file = Number(file)? file : 0;
    rank = Number(rank)? rank : 0;
    return new Square(this.file + file, this.rank + rank);
};
Run Code Online (Sandbox Code Playgroud)

参考: http: //javascript.crockford.com/prototypal.html

话虽如此,许多顶级项目都使用其他模式,包括原型模式。