Skip to content

Commit

Permalink
stage 11
Browse files Browse the repository at this point in the history
  • Loading branch information
jacekkopecky committed Mar 26, 2020
1 parent f9780df commit 28a113b
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 19 deletions.
35 changes: 23 additions & 12 deletions stages/classes.mjs
Original file line number Diff line number Diff line change
@@ -1,39 +1,50 @@
export class Shape {
constructor(x, y, col) {
this.x = x;
this.y = y;
this.col = col;
this._x = x;
this._y = y;
this._col = col;
}

get x() {
return this._x;
}

set x(val) {
if (typeof val !== 'number') {
throw new TypeError('x must be a number');
}
this._x = val;
}

moveBy(x, y) {
this.x += x;
this.y += y;
this._x += x;
this._y += y;
}
}

export class Rectangle extends Shape {
constructor(x, y, width, height, col) {
super(x, y, col);
this.width = width;
this.height = height;
this._width = width;
this._height = height;
}

draw(ctx) {
ctx.fillStyle = this.col;
ctx.fillRect(this.x, this.y, this.width, this.height);
ctx.fillStyle = this._col;
ctx.fillRect(this._x, this._y, this._width, this._height);
}
}

export class Circle extends Shape {
constructor(x, y, r, col) {
super(x, y, col);
this.r = r;
this._r = r;
}

draw(ctx) {
ctx.fillStyle = this.col;
ctx.fillStyle = this._col;
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI);
ctx.arc(this._x, this._y, this._r, 0, 2 * Math.PI);
ctx.fill();
}
}
13 changes: 6 additions & 7 deletions stages/index.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
'use strict';
/**
* Adding functions to a superclass makes them available
* to all classes that extend it.
*
* Here, we use `moveBy()` on rectangles and circles
* even though it is only defined on Shape.
* Getters and setters can perform custom
* code when a property is read or written.
*/

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

for (const s of shapes) {
s.x = 50;
s.draw(ctx);
s.moveBy(110, 30);
s.draw(ctx);

// the following line would throw an error because 'hi' is not a number:
// s.x = 'hi';
}

0 comments on commit 28a113b

Please sign in to comment.