1
1
'use strict' ;
2
2
/**
3
- * We use the `class` keyword to define a class
4
- * before we create instances of it (objects).
3
+ * Objects can contain methods.
5
4
*
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 .
8
7
*
9
- * They are then drawn as before.
8
+ * Methods have access to instance
9
+ * properties by using `this`.
10
10
*/
11
11
12
12
class Rectangle {
@@ -17,20 +17,19 @@ class Rectangle {
17
17
this . height = height ;
18
18
this . col = col ;
19
19
}
20
+
21
+ draw ( ctx ) {
22
+ ctx . fillStyle = this . col ;
23
+ ctx . fillRect ( this . x , this . y , this . width , this . height ) ;
24
+ }
20
25
}
21
26
22
27
// create the two rectangle objects
23
28
const rect1 = new Rectangle ( 100 , 50 , 100 , 200 , 'crimson' ) ;
24
29
const rect2 = new Rectangle ( 300 , 150 , 100 , 200 , 'steelblue' ) ;
25
30
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
-
32
31
// get a handle on the drawing canvas
33
32
const ctx = document . querySelector ( 'canvas' ) . getContext ( '2d' ) ;
34
33
35
- drawRect ( ctx , rect1 ) ;
36
- drawRect ( ctx , rect2 ) ;
34
+ rect1 . draw ( ctx ) ;
35
+ rect2 . draw ( ctx ) ;
0 commit comments