File tree Expand file tree Collapse file tree 2 files changed +16
-6
lines changed Expand file tree Collapse file tree 2 files changed +16
-6
lines changed Original file line number Diff line number Diff 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 ( ) ;
Original file line number Diff line number Diff line change 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
78import { Circle , Rectangle } from './classes.mjs' ;
@@ -18,9 +19,6 @@ const shapes = [
1819const ctx = document . querySelector ( 'canvas' ) . getContext ( '2d' ) ;
1920
2021for ( 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}
You can’t perform that action at this time.
0 commit comments