DayJs源码(三)Dayjs类初始化

看完了dayjs函数,接下来就看 Dayjs类。

先来看类初始化部分

const parseDate = (cfg) => {
  const { date, utc } = cfg // 解构出date
  if (date === null) return new Date(NaN) // null is invalid
  if (Utils.u(date)) return new Date() // today // 这是不传值的情况,Utils.u对应utils.js中的isUndefined方法
  if (date instanceof Date) return new Date(date) // 传入了时间
  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) // 将语言赋值
    this.parse(cfg) // for plugin
  }

  parse(cfg) {
    this.$d = parseDate(cfg) // 解析参数并返回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()
  }
  ...
}

构造函数中将语言方式赋值给$L,调用parse方法解析cfg参数,具体可见代码注释。

init方法中就是解构出解析完存储的date,调用JavaScript的Date原生方法来获取年,月,日等参数。

接下来就是构造函数内各个API的代码。

下一篇 : DayJs源码(四)Dayjs类中API

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容