Skip to content

Commit

Permalink
fix: Do not store the Date object instance passed to the dayjs function
Browse files Browse the repository at this point in the history
If the Date object instance is modified later, it will affect the the dayjs instance too. It will modify its internal this.$d object and make it inconsistent with the other this.$* variables. It will break the immutability of dayjs instances.
  • Loading branch information
prantlf committed Sep 29, 2018
1 parent 81df54e commit 08d518c
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 6 deletions.
17 changes: 11 additions & 6 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,15 @@ const dayjs = (date, c) => {
}
}
const cfg = c || {}
if (date instanceof Date && cfg.cloneDate !== false) {
date = new Date(date)
}
cfg.date = date
return new Dayjs(cfg) // eslint-disable-line no-use-before-define
}

const wrapper = (date, instance) => dayjs(date, { locale: instance.$L, utc: instance.$u })
const wrapper = (date, instance, cloneDate) =>
dayjs(date, { locale: instance.$L, utc: instance.$u, cloneDate })

const Utils = U // for plugin use
Utils.parseLocale = parseLocale
Expand Down Expand Up @@ -184,16 +188,17 @@ class Dayjs {
const date = this.$u
? new Date(Date.UTC(this.$y, m, d))
: new Date(this.$y, m, d)
const ins = wrapper(date, this)
const ins = wrapper(date, this, false)
return isStartOf ? ins : ins.endOf(C.D)
}
const instanceFactorySet = (slice) => {
const argumentStart = [0, 0, 0, 0]
const argumentEnd = [23, 59, 59, 999]
return wrapper(this.toDate()[setMethods[slice]].apply( // eslint-disable-line prefer-spread
this.toDate(),
const date = this.toDate()
return wrapper(date[setMethods[slice]].apply( // eslint-disable-line prefer-spread
date,
isStartOf ? argumentStart.slice(slice) : argumentEnd.slice(slice)
), this)
), this, false)
}
switch (unit) {
case C.Y:
Expand Down Expand Up @@ -443,7 +448,7 @@ class Dayjs {
}

clone() {
return wrapper(this.toDate(), this)
return wrapper(this.toDate(), this, false)
}

toDate() {
Expand Down
8 changes: 8 additions & 0 deletions test/parse.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,14 @@ it('Creating a new instance from another instance retains the UTC mode', () => {
expect(instance.minute()).toEqual(source.minute())
})

it('Original Date object does not affect the dayjs instance', () => {
const original = new Date()
const instance = dayjs(original)
const internal = instance.toDate()
original.setTime(original.getTime() - 3600000)
expect(instance.toDate()).toEqual(internal)
})

it('Clone not affect each other', () => {
const base = dayjs(20170101)
const year = base.year()
Expand Down

0 comments on commit 08d518c

Please sign in to comment.