版权声明:本文首发 http://asing1elife.com ,转载请注明出处。 https://blog.csdn.net/asing1elife/article/details/82820605
虽然ES6之后可以实现JavaScript创建Class,但自身并不提供函数重载,所以无法直接创建多个构造函数
更多精彩
- 更多技术博客,请移步 asing1elife’s blog
解决
- 原理则是对一个构造函数的传值进行类型判断,从而实现根据类型的不同调用不同的构造函数方法体
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
}
}