天天看點

es6為類建立多個構造函數

版權聲明:本文首發 http://asing1elife.com ,轉載請注明出處。 https://blog.csdn.net/asing1elife/article/details/82820605

雖然ES6之後可以實作JavaScript建立Class,但自身并不提供函數重載,是以無法直接建立多個構造函數

更多精彩

解決

  1. 原理則是對一個構造函數的傳值進行類型判斷,進而實作根據類型的不同調用不同的構造函數方法體
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
  }
}
                

繼續閱讀