Skip to content

Commit 28a113b

Browse files
committed
stage 11
1 parent f9780df commit 28a113b

File tree

2 files changed

+29
-19
lines changed

2 files changed

+29
-19
lines changed

stages/classes.mjs

Lines changed: 23 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,50 @@
11
export class Shape {
22
constructor(x, y, col) {
3-
this.x = x;
4-
this.y = y;
5-
this.col = col;
3+
this._x = x;
4+
this._y = y;
5+
this._col = col;
6+
}
7+
8+
get x() {
9+
return this._x;
10+
}
11+
12+
set x(val) {
13+
if (typeof val !== 'number') {
14+
throw new TypeError('x must be a number');
15+
}
16+
this._x = val;
617
}
718

819
moveBy(x, y) {
9-
this.x += x;
10-
this.y += y;
20+
this._x += x;
21+
this._y += y;
1122
}
1223
}
1324

1425
export class Rectangle extends Shape {
1526
constructor(x, y, width, height, col) {
1627
super(x, y, col);
17-
this.width = width;
18-
this.height = height;
28+
this._width = width;
29+
this._height = height;
1930
}
2031

2132
draw(ctx) {
22-
ctx.fillStyle = this.col;
23-
ctx.fillRect(this.x, this.y, this.width, this.height);
33+
ctx.fillStyle = this._col;
34+
ctx.fillRect(this._x, this._y, this._width, this._height);
2435
}
2536
}
2637

2738
export class Circle extends Shape {
2839
constructor(x, y, r, col) {
2940
super(x, y, col);
30-
this.r = r;
41+
this._r = r;
3142
}
3243

3344
draw(ctx) {
34-
ctx.fillStyle = this.col;
45+
ctx.fillStyle = this._col;
3546
ctx.beginPath();
36-
ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI);
47+
ctx.arc(this._x, this._y, this._r, 0, 2 * Math.PI);
3748
ctx.fill();
3849
}
3950
}

stages/index.js

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,7 @@
11
'use strict';
22
/**
3-
* Adding functions to a superclass makes them available
4-
* to all classes that extend it.
5-
*
6-
* Here, we use `moveBy()` on rectangles and circles
7-
* even though it is only defined on Shape.
3+
* Getters and setters can perform custom
4+
* code when a property is read or written.
85
*/
96

107
import { Circle, Rectangle } from './classes.mjs';
@@ -21,7 +18,9 @@ const shapes = [
2118
const ctx = document.querySelector('canvas').getContext('2d');
2219

2320
for (const s of shapes) {
21+
s.x = 50;
2422
s.draw(ctx);
25-
s.moveBy(110, 30);
26-
s.draw(ctx);
23+
24+
// the following line would throw an error because 'hi' is not a number:
25+
// s.x = 'hi';
2726
}

0 commit comments

Comments
 (0)