Prepare Interview

Mock Exams

Make Homepage

Bookmark this page

Subscribe Email Address

Question: What is User-Defined class in Javascript?
Answer: can define new classes, but the notation is awkward
simply define a function that serves as a constructor
specify data fields & methods using this

no data hiding: can't protect data or methods

function Die(sides)
{
this.numSides = sides;
this.numRolls = 0;
this.Roll = Roll;
}

function Roll()
{
this.numRolls++;
return Math.floor(Math.random()*this.numSides) + 1;
}

die6 = new Die(6);
die8 = new Die(8);

roll6 = -1; // dummy value to start loop
roll8 = -2; // dummy value to start loop
while (roll6 != roll8) {
roll6 = die6.Roll();
roll8 = die8.Roll();

document.write("6-sided: " + roll6 +
"    " +
"8-sided: " + roll8 + "
");
}
Is it helpful? Yes No

Most helpful rated by users:

©2025 WithoutBook