Skip to content

Commit 6bbc890

Browse files
committed
stage 12
1 parent 28a113b commit 6bbc890

File tree

2 files changed

+16
-6
lines changed

2 files changed

+16
-6
lines changed

stages/classes.mjs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,10 @@ export class Shape {
1616
this._x = val;
1717
}
1818

19+
get area() {
20+
throw new Error('area is not a property of this shape');
21+
}
22+
1923
moveBy(x, y) {
2024
this._x += x;
2125
this._y += y;
@@ -29,6 +33,10 @@ export class Rectangle extends Shape {
2933
this._height = height;
3034
}
3135

36+
get area() {
37+
return this._width * this._height;
38+
}
39+
3240
draw(ctx) {
3341
ctx.fillStyle = this._col;
3442
ctx.fillRect(this._x, this._y, this._width, this._height);
@@ -41,6 +49,10 @@ export class Circle extends Shape {
4149
this._r = r;
4250
}
4351

52+
get area() {
53+
return Math.PI * this._r ** 2;
54+
}
55+
4456
draw(ctx) {
4557
ctx.fillStyle = this._col;
4658
ctx.beginPath();

stages/index.js

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
'use strict';
22
/**
3-
* Getters and setters can perform custom
4-
* code when a property is read or written.
3+
* Getters can be used for computed properties.
4+
*
5+
* Here, shapes come with `.area`.
56
*/
67

78
import { Circle, Rectangle } from './classes.mjs';
@@ -18,9 +19,6 @@ const shapes = [
1819
const ctx = document.querySelector('canvas').getContext('2d');
1920

2021
for (const s of shapes) {
21-
s.x = 50;
2222
s.draw(ctx);
23-
24-
// the following line would throw an error because 'hi' is not a number:
25-
// s.x = 'hi';
23+
console.log(s.area);
2624
}

0 commit comments

Comments
 (0)