1
+ /**
2
+ * public / private / protected
3
+ * getter / setter
4
+ */
5
+
6
+ ( function ( ) {
7
+
8
+ class A {
9
+ protected num : number ;
10
+ // 语法糖,在构造函数中定义属性,public age: number
11
+ constructor ( num : number , public age : number ) {
12
+ this . num = num ;
13
+ this . age = age ;
14
+ }
15
+ }
16
+ class B extends A {
17
+ test ( ) {
18
+ console . log ( this . num ) ;
19
+ }
20
+ }
21
+ const b = new B ( 777 , 18 ) ;
22
+ // b.num = 1;
23
+
24
+
25
+ class Person {
26
+ // 默认 public
27
+ public age : number = 30 ;
28
+ public readonly name : string = 'csxiaoyao' ;
29
+ private _hobby : Array < string > ;
30
+
31
+ constructor ( age : number ) {
32
+ this . age = age ;
33
+ this . _hobby = [ ] ;
34
+ }
35
+
36
+ // getter / setter
37
+ /*
38
+ getHobby() {
39
+ return this._hobby;
40
+ }
41
+ setHobby(hobby: Array<string>) {
42
+ this._hobby = hobby;
43
+ }
44
+ */
45
+ get hobby ( ) {
46
+ return this . _hobby ;
47
+ }
48
+ set hobby ( hobby : Array < string > ) {
49
+ this . _hobby = hobby ;
50
+ }
51
+ }
52
+
53
+ const per = new Person ( 18 ) ;
54
+ // getter
55
+ console . log ( per . hobby ) ;
56
+
57
+
58
+ } ) ( ) ;
0 commit comments