javascript - How can I create a method in JS like an abstract method in Java? - Stack Overflow

admin2025-04-18  0

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.

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.

Share edited Nov 19, 2011 at 17:21 Jesse Rusak 57.2k12 gold badges102 silver badges102 bronze badges asked Nov 19, 2011 at 17:14 Asher SabanAsher Saban 4,80313 gold badges49 silver badges61 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 10

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
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1744950030a276277.html

最新回复(0)