or
class Circle {
constructor(radius, color) {
this.radius = radius;
this.color = color;
}
area() {
const area = this.radius * this.radius * Math.PI;
return area;
}
paint() {
console.log(`Painting with color ${this.color}`);
}
}
const circle = new Circle(2, "red");
const area = circle.area();
console.log(area);
💡Can you see there is code repetition here and in the Rectangle class?
class Shape {
constructor(color) {
this.color = color;
}
paint() {
console.log(`Painting with color ${this.color}`);
}
area() {
throw new Error("The area method must be implemented in the subclass");
}
getDescription() {
return `A shape with color ${this.color}`;
}
}
class Rectangle extends Shape {
constructor(width, height, color) {
super(color); // Call the parent class constructor to set the color
this.width = width;
this.height = height;
}
area() {
return this.width * this.height;
}
getDescription() {
return `A rectangle with width ${this.width}, height ${this.height}, and color ${this.color}`;
}
}
class Circle extends Shape {
constructor(radius, color) {
super(color); // Call the parent class constructor to set the color
this.radius = radius;
}
area() {
return Math.PI * this.radius * this.radius;
}
getDescription() {
return `A circle with radius ${this.radius} and color ${this.color}`;
}
}
Play trying with it
const circle = new Circle(20);
console.log(circle.area());
Q: Write code that
- logs
hi
after 1 second - logs
hello
3 seconds afterstep 1
- logs
hello there
5 seconds afterstep 2
Solution (has callback hell)
setTimeout(function () {
console.log("hi");
setTimeout(function () {
console.log("hello");
setTimeout(function () {
console.log("hello there");
}, 5000);
}, 3000);
}, 1000);
Alt solution (doesnt really have callback hell)
function step3Done() {
console.log("hello there");
}
function step2Done() {
console.log("hello");
setTimeout(step3Done, 5000);
}
function step1Done() {
console.log("hi");
setTimeout(step2Done, 3000);
}
setTimeout(step1Done, 1000);
Now use the promisified
version we saw in the last slide
function setTimeoutPromisified(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
Solution #1 (has callback hell)
function setTimeoutPromisified(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
setTimeoutPromisified(1000).then(function () {
console.log("hi");
setTimeoutPromisified(3000).then(function () {
console.log("hello");
setTimeoutPromisified(5000).then(function () {
console.log("hello there");
});
});
});
Alt solution
setTimeoutPromisified(1000)
.then(function () {
console.log("hi");
return setTimeoutPromisified(3000);
})
.then(function () {
console.log("hello");
return setTimeoutPromisified(5000);
})
.then(function () {
console.log("hello there");
});