es6为类创建多个构造函数

虽然ES6之后可以实现JavaScript创建Class,但自身并不提供函数重载,所以无法直接创建多个构造函数

解决

  1. 原理则是对一个构造函数的传值进行类型判断,从而实现根据类型的不同调用不同的构造函数方法体
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
export default class User {
  
  constructor (obj) {
    if (typeof obj === 'string') {
      this._constructorSimple(obj)
    } else if (typeof obj === 'object') {
      this._constructorComplex(obj)
    }
  }
  
  _constructorSimple (id) {
    this.id = id
    this.code = ''
    this.name = ''
    this.sex = ''
    this.age = 20
    this.birthday = ''
    this.address = ''
    this.selectedGroup = []
    this.selectedRoles = []
  }
  
  _constructorComplex (data) {
    this.id = data.id
    this.code = data.code
    this.name = data.name
    this.sex = data.sex
    this.age = data.age
    this.birthday = data.birthday
    this.address = data.address
    this.selectedGroup = data.groupIds.split(',')
    this.selectedRoles = data.selectedRoles
  }
}