Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a method in JS like an abstract method in Java?

Tags:

javascript

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.

like image 980
Asher Saban Avatar asked Nov 19 '11 17:11

Asher Saban


1 Answers

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
like image 62
Felix Kling Avatar answered Sep 27 '22 21:09

Felix Kling