11'use strict' ;
22/**
3- * We use the `class` keyword to define a class
4- * before we create instances of it (objects).
3+ * Objects can contain methods.
54 *
6- * We define the `Rectangle` class and create two
7- * instances of it .
5+ * Here, we move the `drawRect` function into the class
6+ * definition as a `draw` method .
87 *
9- * They are then drawn as before.
8+ * Methods have access to instance
9+ * properties by using `this`.
1010 */
1111
1212class Rectangle {
@@ -17,20 +17,19 @@ class Rectangle {
1717 this . height = height ;
1818 this . col = col ;
1919 }
20+
21+ draw ( ctx ) {
22+ ctx . fillStyle = this . col ;
23+ ctx . fillRect ( this . x , this . y , this . width , this . height ) ;
24+ }
2025}
2126
2227// create the two rectangle objects
2328const rect1 = new Rectangle ( 100 , 50 , 100 , 200 , 'crimson' ) ;
2429const rect2 = new Rectangle ( 300 , 150 , 100 , 200 , 'steelblue' ) ;
2530
26- // draw a rectangle
27- function drawRect ( c , r ) {
28- c . fillStyle = r . col ;
29- c . fillRect ( r . x , r . y , r . width , r . height ) ;
30- }
31-
3231// get a handle on the drawing canvas
3332const ctx = document . querySelector ( 'canvas' ) . getContext ( '2d' ) ;
3433
35- drawRect ( ctx , rect1 ) ;
36- drawRect ( ctx , rect2 ) ;
34+ rect1 . draw ( ctx ) ;
35+ rect2 . draw ( ctx ) ;
0 commit comments