Moment: Enable all non-mutation functionality after Object.freeze()

Created on 14 Jan 2016  ·  4Comments  ·  Source: moment/moment

Splitting out @kruncher's request from the discussion on #1754:

I have been using Object.freeze on moment instances and this has generally achieved what I have needed; except I just discovered that the following fails:

let now = Object.freeze(moment());
if (now.isSameOrBefore(anotherTime)) { // throws exception
}

The exception:

TypeError: Can't add property _isValid, object is not extensible
 at valid__isValid (C:\git\quick-test\node_modules\moment\moment.js:93:24)
 at Moment.moment_valid__isValid [as isValid] (C:\git\quick-test\node_modules\moment\moment.js:2195:16)
 at Moment.isSame (C:\git\quick-test\node_modules\moment\moment.js:1945:44)
 at Moment.isSameOrBefore (C:\git\quick-test\node_modules\moment\moment.js:1962:21)

Can this be fixed so that Object.freeze can be used when desired?

Help Wanted

All 4 comments

const moment = require('moment')
const today = Object.freeze(moment()); 
today.toString()
   => 'Tue May 02 2017 10:04:52 GMT-0400'
today.add(1, 'day')
   => moment("2017-05-03T10:04:52.889")
today.toString()
  => 'Wed May 03 2017 10:04:52 GMT-0400'

Maybe I'm missing something but Object.freeze doesn't seem to work for me at all on latest release. I know that there's a large push for immutability in 3.x but in the meantime is there reliability in Object.freeze? /

Node version: 6.10 (~lts)
Moment version: 2.18.1

@butterflyhug - I'm unable to reproduce the TypeError, even in strict mode.

@SeanDunford - this seems weird. I don't know if you can trust immutability in 2.x.

I would love help understanding why this object seems mutable, even if frozen or deepFrozen.

@marwahaha - We've switched to Luxon now. At the time we weren't ready to use 3.x.

Ok, I will close and assume Object.freeze does not work for moments in 2.x.

Was this page helpful?
0 / 5 - 0 ratings