Skip to content

类是用于创建对象的模板。他们用代码封装数据以处理该数据。

定义类的两种方式

类声明

js
class Foo {}

类表达式

js
const Foo = class {} // 未命名 / 匿名类
Foo.name // output: Foo
const Bar = class Baz {} // 命名类
Bar.name // output: Baz

类体和方法定义

js
class Rectangle { // 类体执行在严格模式下
  constructor (width, height) {
    this.width = width
    this.height = height
  }

  // 静态属性,只能通过 Rectangle.dispalyName 访问。
  static dispalyName = 'Rectangle'
  
  // 静态方法,只能通过 Rectangle.sayRectangle() 执行。
  static sayRectangle () {
    console.log('Rectangle')
  }

  // getter
  get area () {
    return this.calcArea()
  }

  // Foo.prototype.calcArea
  calcArea () {
    return this.width * this.height
  }
}

// 静态的或原型的数据属性必须定义在类定义的外面。
Rectangle.staticWidth = 20
Rectangle.prototype.prototypeWidth = 25