Political Game Example

Here is an example of using a dynamic property in the context of a political game in JavaScript:

function PoliticalGame(candidate) {
  this.candidate = candidate;
}

PoliticalGame.prototype.winElection = function() {
  this.candidate.victories++;
}

const candidate1 = { name: "John Smith", victories: 0 };
const game1 = new PoliticalGame(candidate1);
game1.winElection();
console.log(candidate1.victories); // Output: 1

const candidate2 = { name: "Jane Doe", victories: 0 };
const game2 = new PoliticalGame(candidate2);
game2.winElection();
console.log(candidate2.victories); // Output: 1

In this example, the PoliticalGame constructor function is defined with a single argument, candidate. The winElection method is added to the prototype of the PoliticalGame constructor, which increases the victories property of the candidate object by 1.

Two candidates, candidate1 and candidate2, are created using object literals. Each candidate has a name property and a victories property, which is initially set to 0.

Two instances of the PoliticalGame are created using the new operator, with candidate1 and candidate2 as the arguments. The winElection method is called on each instance of the game, which increases the victories property of the corresponding candidate object by 1.

The dynamic property in this example is the victories property of the candidate objects. It is not defined as a property of the PoliticalGame constructor function, but it is created and modified by the winElection method. This allows the PoliticalGame to track the number of victories of each candidate, even though the candidates are different objects with different properties.

Last updated