Hide & Seek Game
Here is an example of reading a dynamic property in the context of a hide and seek computer game in JavaScript:
In this example, the Player
constructor function is defined with a single argument, name
. The found
method is added to the prototype of the Player
constructor, which increases the score
property of the player object by 1.
Two player objects, player1
and player2
, are created using the Player
constructor. Each player has a name
property and a score
property, which is initially set to 0.
The game is simulated in a while
loop, which continues until either player1
or player2
reaches a score of 10. At each iteration of the loop, a random player is chosen to be the winner using the ternary operator, and the found
method is called on that player to increase their score.
After the loop finishes, the scores of both players are logged to the console. The score
property is a dynamic property of the player objects, as it is not defined as a property of the Player
constructor function, but is created and modified by the found
method. This allows the game to track the score of each player, even though the players are different objects with different properties.
Last updated