类定义

类名要以大写字母开头

  1. class animal {}
  2. const dog = new animal() // ✗ 错误
  3. class Animal {}
  4. const dog = new Animal() // ✓ 正确

避免对类名重新赋值

  1. class Dog {}
  2. Dog = 'Fido' // ✗ 错误

子类的构造器中一定要调用 super

  1. class Dog {
  2. constructor () {
  3. super() // ✗ 错误
  4. }
  5. }
  6. class Dog extends Mammal {
  7. constructor () {
  8. super() // ✓ 正确
  9. }
  10. }

使用 this 前请确保 super() 已调用

  1. class Dog extends Animal {
  2. constructor () {
  3. this.legs = 4 // ✗ 错误
  4. super()
  5. }
  6. }

禁止多余的构造器

  1. class Car {
  2. constructor () { // ✗ 错误
  3. }
  4. }
  5. class Car {
  6. constructor () { // ✗ 错误
  7. super()
  8. }
  9. }

类中不要定义冗余的属性

  1. class Dog {
  2. bark () {}
  3. bark () {} // ✗ 错误
  4. }

无参的构造函数调用时要带上括号

  1. function Animal () {}
  2. const dog = new Animal // ✗ 错误
  3. const dog = new Animal() // ✓ 正确

new 创建对象实例后需要赋值给变量

  1. new Character() // ✗ 错误
  2. const character = new Character() // ✓ 正确