---
url: /docs/guide/usage/linter/rules/unicorn/prefer-class-fields.md
---

### 作用

优先使用类字段声明，而不是在构造函数中通过 `this` 赋值来设置静态值。

### 为什么这样不好？

类字段声明比在构造函数中将静态值赋给 `this` 更易读，也更不容易出错。使用类字段可以让构造函数更简洁，并且让意图更明确。

### 示例

以下是此规则的**错误**代码示例：

```ts
class Foo {
  constructor() {
    this.bar = 1;
  }
}

class MyError extends Error {
  constructor(message: string) {
    super(message);
    this.name = "MyError";
  }
}

class Foo {
  foo = "foo";
  constructor() {
    this.foo = "bar";
  }
}
```

以下是此规则的**正确**代码示例：

```js
class Foo {
  bar = 1;
}

class MyError extends Error {
  name = "MyError";
}

class Foo {
  foo = "bar";
}
```

## 如何使用

## 版本

此规则于 v1.20.0 中加入。

## 参考资料
