Give an example of a time that you used Prototypal OO in JavaScript.

Experience Level: Medior
Tags: JavaScript

Answer

One example of a time that I used Prototypal OO in JavaScript was when I was working on a project that required creating multiple instances of an object with similar properties and methods. Instead of creating each instance individually, I used prototypal inheritance to create a base object and then created new instances by inheriting from that base object.

For example, let's say I was creating a game that had multiple characters with similar properties and methods, such as health, attack power, and a method to attack. I could create a base object called "Character" with these properties and methods:


function Character() {
  this.health = 100;
  this.attackPower = 10;
}

Character.prototype.attack = function(target) {
  target.health -= this.attackPower;
}

Then, I could create new instances of the "Character" object by using the "Object.create" method to inherit from the base object:


var player1 = Object.create(Character);
player1.name = "Player 1";

var player2 = Object.create(Character);
player2.name = "Player 2";

Now, both "player1" and "player2" have the same properties and methods as the "Character" object, but can also have their own unique properties, such as a name. This approach saved time and made the code more efficient by avoiding repetitive code.

Related JavaScript job interview questions

Comments

No Comments Yet.
Be the first to tell us what you think.