class Square {
constructor(width) {
this.width = width;
this.height = width;
this.numOfRequestsForArea = 0;
}
get area() {
this.numOfRequestsForArea++;
return this.width * this.height;
}
set area(area) {
this.width = Math.sqrt(area);
this.height = this.width;
}
}
let square1 = new Square(4);
console.log(square1.area);
square1.area = 25;
console.log(square1.width);
console.log(square1.area);
console.log(square1.area);
console.log(square1.area);
console.log(square1.area);
console.log(square1.area);
console.log(square1.numOfRequestsForArea);
Static methods
class Square {
constructor(width) {
this.width = width;
this.height = width;
}
static equals(a, b) {
return a.width * a.height === b.width * b.height;
}
static isValidDimensions(width, height) {
return width === height;
}
}
let square1 = new Square(8);
let square2 = new Square(8);
console.log(Square.isValidDimensions(7, 6));
Parent and Child Class
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
describe() {
console.log(`i am ${this.name} and i am ${this.age}`);
}
}
class Programmer extends Person {
constructor(name, age, yearsOfExperience) {
super(name, age);
this.yearsOfExperience = yearsOfExperience;
}
code() {
console.log(`${this.name}is coding`);
}
}
let person1 = new Person('jeff', 45);
let programmer1 = new Programmer('dom', 56, 12);
const programmers = [
new Programmer('Dom', 56, 12),
new Programmer('Jeff', 24, 4),
];
function developSoftware(programmers) {
for (let programmer of programmers) {
programmer.code();
}
}
developSoftware(programmers);
Redefining a method inside a derived .. what
class Animal {
constructor(name) {
this.name = name;
}
makeSound() {
console.log('generic animal sound');
}
}
class Dog extends Animal {
constructor(name) {
super(name);
}
makeSound() {
super.makeSound();
console.log('woof woof');
}
}
const a1 = new Animal('dom');
a1.makeSound();
const a2 = new Dog('jeff');
a2.makeSound();