How to create a method in JS as an abstract method in Java?

I am building a little game - rock paper scissors.

I have a prototype - RPSPlayer , and I have two types of players: Player1 , Player2 (player1 and player2 are objects with an RPSPlayer prototype), each player plays with a function: Player1.play() .

Each player has a different strategy for the game. So I need 2 implementations for play() . If it were Java, I would create an abstract RPSPlayer class with an abstract play() method and two other classes that inherit from RPSPlayer ; each of them will have its own implementation for play() .

My question is: what is the right way to do this in JS? I hope I made it clear, thanks to everyone.

+6
source share
1 answer

You can define an empty function in the prototype:

 RPSPlayer.prototype.play = function() {}; 

or if you want to force this function, you can make it throw an error:

 RPSPlayer.prototype.play = function() { throw new Error('Call to abstract method play.'); }; 

Here's how the Google Closure library does this with the goog.abstractMethod function:

 goog.abstractMethod = function() { throw Error('unimplemented abstract method'); }; 

which should be used as

 Foo.prototype.bar = goog.abstractMethod 
+10
source

Source: https://habr.com/ru/post/901899/


All Articles