看完了dayjs函數(shù),接下來(lái)就看 Dayjs類(lèi)嚎卫。
先來(lái)看類(lèi)初始化部分
const parseDate = (cfg) => {
const { date, utc } = cfg // 解構(gòu)出date
if (date === null) return new Date(NaN) // null is invalid
if (Utils.u(date)) return new Date() // today // 這是不傳值的情況勃救,Utils.u對(duì)應(yīng)utils.js中的isUndefined方法
if (date instanceof Date) return new Date(date) // 傳入了時(shí)間
if (typeof date === 'string' && !/Z$/i.test(date)) { // 如果傳入date為string
const d = date.match(C.REGEX_PARSE) //C.REGEX_PARSE = /^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[^0-9]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/
if (d) {
const m = d[2] - 1 || 0
const ms = (d[7] || '0').substring(0, 3)
if (utc) {
return new Date(Date.UTC(d[1], m, d[3]
|| 1, d[4] || 0, d[5] || 0, d[6] || 0, ms))
}
return new Date(d[1], m, d[3]
|| 1, d[4] || 0, d[5] || 0, d[6] || 0, ms)
}
}
return new Date(date) // everything else
}
class Dayjs {
constructor(cfg) {
this.$L = parseLocale(cfg.locale, null, true) // 將語(yǔ)言賦值
this.parse(cfg) // for plugin
}
parse(cfg) {
this.$d = parseDate(cfg) // 解析參數(shù)并返回date值
this.$x = cfg.x || {}
this.init()
}
init() {
const { $d } = this
this.$y = $d.getFullYear()
this.$M = $d.getMonth()
this.$D = $d.getDate()
this.$W = $d.getDay()
this.$H = $d.getHours()
this.$m = $d.getMinutes()
this.$s = $d.getSeconds()
this.$ms = $d.getMilliseconds()
}
...
}
構(gòu)造函數(shù)中將語(yǔ)言方式賦值給$L,調(diào)用parse方法解析cfg參數(shù),具體可見(jiàn)代碼注釋甲脏。
init方法中就是解構(gòu)出解析完存儲(chǔ)的date眶熬,調(diào)用JavaScript的Date原生方法來(lái)獲取年,月块请,日等參數(shù)娜氏。
接下來(lái)就是構(gòu)造函數(shù)內(nèi)各個(gè)API的代碼。