Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 31 additions & 1 deletion advanced/class.md
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ let a = new Animal('Jack');
```ts
class Animal {
public name;
private constructor (name) {
protected constructor (name) {
this.name = name;
}
}
Expand All @@ -291,6 +291,36 @@ class Animal {
}
```

### readonly

只读属性关键字,只允许出现在属性声明或索引签名中。

```ts
class Animal {
readonly name;
public constructor(name) {
this.name = name;
}
}

let a = new Animal('Jack');
console.log(a.name); // Jack
a.name = 'Tom';

// index.ts(10,3): TS2540: Cannot assign to 'name' because it is a read-only property.
```

注意如果 `readonly` 和其他访问修饰符同时存在的话,需要写在其后面。

```ts
class Animal {
// public readonly name;
public constructor(public readonly name) {
this.name = name;
}
}
```

### 抽象类

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