Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit fb227f8

Browse files
author
victorsun
committed
upd:ts
1 parent 5e903d8 commit fb227f8

File tree

3 files changed

+96
-1
lines changed

3 files changed

+96
-1
lines changed

‎18-TypeScript/04-oop/04-修饰符.ts

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
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+
})();

‎18-TypeScript/04-oop/05-泛型.ts

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
2+
/**
3+
* 定义函数或类时,不明确的类型可以使用泛型,在执行时确定类型
4+
* fn<T> 定义泛型T
5+
*/
6+
function fn<T>(a: T): T {
7+
return a;
8+
}
9+
// 泛型自动推断
10+
fn(10);
11+
// 指定泛型
12+
fn<string>('hello');
13+
14+
// 定义多个泛型
15+
function fn2<T, K>(a: T, b: K): T {
16+
console.log(b);
17+
return a;
18+
}
19+
fn2<number, string>(123, 'hello');
20+
21+
// 限制泛型范围
22+
interface Inter {
23+
length: number;
24+
}
25+
function fn3<T extends Inter>(a: T): number {
26+
return a.length;
27+
}
28+
fn3({length:10});
29+
30+
// class
31+
class MyClass<T> {
32+
name: T;
33+
constructor(name: T) {
34+
this.name = name;
35+
}
36+
}
37+
const mc = new MyClass<string>('csxiaoyao');

‎18-TypeScript/04-oop/index.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,6 @@
66
<title>TS-OOP</title>
77
</head>
88
<body>
9-
<script src="dist/02-abstract.js"></script>
9+
<script src="dist/05-泛型.js"></script>
1010
</body>
1111
</html>

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /