Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit a66f991

Browse files
committed
feat: Modifies constructors and constructor parameters
1 parent 9e9faa5 commit a66f991

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

advanced/class.md

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -239,6 +239,58 @@ class Cat extends Animal {
239239
}
240240
```
241241

242+
当构造函数修饰为 `private` 时,该类不允许被继承或者实例化:
243+
244+
```ts
245+
class Animal {
246+
public name;
247+
private constructor (name) {
248+
this.name = name;
249+
}
250+
}
251+
class Cat extends Animal {
252+
constructor (name) {
253+
super(name);
254+
}
255+
}
256+
257+
let a = new Animal('Jack');
258+
259+
// index.ts(7,19): TS2675: Cannot extend a class 'Animal'. Class constructor is marked as private.
260+
// index.ts(13,9): TS2673: Constructor of class 'Animal' is private and only accessible within the class declaration.
261+
```
262+
263+
当构造函数修饰为 `protected` 时,该类只允许被继承:
264+
265+
```ts
266+
class Animal {
267+
public name;
268+
private constructor (name) {
269+
this.name = name;
270+
}
271+
}
272+
class Cat extends Animal {
273+
constructor (name) {
274+
super(name);
275+
}
276+
}
277+
278+
let a = new Animal('Jack');
279+
280+
// index.ts(13,9): TS2674: Constructor of class 'Animal' is protected and only accessible within the class declaration.
281+
```
282+
283+
修饰符还可以使用在构造函数参数中,等同于类中定义该属性,使代码更简洁。
284+
285+
```ts
286+
class Animal {
287+
// public name: string;
288+
public constructor (public name) {
289+
this.name = name;
290+
}
291+
}
292+
```
293+
242294
### 抽象类
243295

244296
`abstract` 用于定义抽象类和其中的抽象方法。

0 commit comments

Comments
 (0)