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

Skip to content

参数属性 #118

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 12, 2020
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
10 changes: 6 additions & 4 deletions advanced/class.md
Original file line number Diff line number Diff line change
Expand Up @@ -280,20 +280,22 @@ let a = new Animal('Jack');
// index.ts(13,9): TS2674: Constructor of class 'Animal' is protected and only accessible within the class declaration.
```

修饰符还可以使用在构造函数参数中,等同于类中定义该属性,使代码更简洁。
### 参数属性

修饰符和`readonly`还可以使用在构造函数参数中,等同于类中定义该属性同时给该属性赋值,使代码更简洁。

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

### readonly

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

```ts
class Animal {
Expand All @@ -316,7 +318,7 @@ a.name = 'Tom';
class Animal {
// public readonly name;
public constructor(public readonly name) {
this.name = name;
// this.name = name;
}
}
```
Expand Down