JavaScript Classes
Defining Classes
class Player {
constructor(name, dob) {
this.name = name;
this.dob = dob;
this.score = 0;
}
addPoints(points) {
this.score += points;
}
getAge() {
return Math.floor((Date.now() - this.dob.getTime()) / (365 * 86400 * 1000));
}
}
Instantiation
const player = new Player("Brendan Eich", new Date("July 4, 1961"));
console.log(player instanceof Player);
console.log(player.name);
console.log(player.getAge());
console.log(player.score);
player.addPoints(42);
console.log(player.score);
Inheritance
class Person {
constructor(name, dob) {
this.name = name;
this.dob = dob;
}
getAge() {
return Math.floor((Date.now() - this.dob.getTime()) / (365 * 86400 * 1000));
}
}
class Player extends Person {
// Field declaration syntax
score = 0;
addPoints(points) {
this.score += points;
}
}
const player = new Player("Brendan Eich", new Date("July 4, 1961"));
console.log(player instanceof Person);
console.log(player instanceof Player);
console.log(player.name);
console.log(player.getAge());
console.log(player.score);
player.addPoints(42);
console.log(player.score);
Last updated
Was this helpful?