I'm building a small game - rock paper scissors.
I have a prototype - RPSPlayer
and I have two kinds of players: Player1
, Player2
(player1 & player2 are objects with a prototype of RPSPlayer) each player plays with the function: Player1.play()
.
Each player has a different strategy for the game. Thus, I need 2 implementations for play()
. If it was Java, I would create an abstract class RPSPlayer
with an abstract method play()
and 2 other classes which inherit from RPSPlayer
; each of them would have its own implementation for play()
.
My question is: what is the correct way to do it in JS? I hope I made myself clear, thanks everyone.
You can define an empty function on the prototype:
RPSPlayer.prototype.play = function() {};
or if you want to force an implementation of this function, you can make it throw an error:
RPSPlayer.prototype.play = function() {
throw new Error('Call to abstract method play.');
};
This is how the Google Closure library is doing it, with its goog.abstractMethod
function:
goog.abstractMethod = function() {
throw Error('unimplemented abstract method');
};
which is to be used as
Foo.prototype.bar = goog.abstractMethod
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With