What are the benefits of putting stuff on an object's prototype? For example, these two implementations of ChessPiece
seem very similar. What are the trade-offs?
Without prototype
var ChessPiece = function(x, y) {
var self = this;
this.x = x;
this.y = y;
this.getNotation = function() {
return 'abcdefgh'[self.x] + '12345678'[self.y];
};
}
var pawn1 = new ChessPiece(1, 0);
pawn1.getNotation(); // 'b1';
With prototype
var ChessPiece = function(x, y) {
this.x = x;
this.y = y;
}
ChessPiece.prototype.getNotation = function() {
return 'abcdefgh'[this.x] + '12345678'[this.y];
}
var pawn2 = new ChessPiece(1, 1);
pawn2.getNotation(); // 'b2'
To me, the most significant difference is that when getNotation
is on ChessPiece
's prototype, that method is shared by all instances. When it's not on the prototype, there are multiple copies of getNotation
. Does this matter? Is there more I am missing?
As an aside, the reason I prefer the first method is because it is cleaner to write everything in a single constructor function, rather than having to declare ChessPiece
and then assign each method on separate lines. Is there a way to work around that issue, if the latter is preferred?