我如何在moment.js中解决可变性问题? [英] How do I work around mutability in moment.js?
问题描述
我遇到了一个问题,我必须存储一个时刻对象的初始值,但是我遇到了一些问题,我的变量不能随原始对象一起变化。
I've run into a problem where I have to store the initial values of a moment object but I'm having some trouble preventing my variable from changing along with the original object.
不幸的是,Object.freeze()不起作用,因为当我尝试格式化时,moment.js返回无效日期错误。
Unfortunately Object.freeze() doesn't work, because moment.js returns an "Invalid date" error when I try to format that.
推荐答案
NPM上有一个名为冻结时刻的Moment.js插件 - 您可以使用 moment()。freeze()
代替 Object.freeze(moment())
。
There's a Moment.js plugin on NPM called frozen-moment - You could use moment().freeze()
in place of Object.freeze(moment())
.
否则,vanilla Moment.js有一个 clone
方法,它可以帮助你避免可变性问题,所以你可以做这样的事情:
Otherwise, vanilla Moment.js has a clone
method that should help you avoid mutability problems, so you could do something like this:
var a = moment(),
b = a.clone(); // or moment(a)
更新:
我写这个答案已经两年了。在这个时候,另一个处理日期的图书馆浮出水面并获得了很大的吸引力: https://date-fns.org /
It has been two years since I wrote this answer. In this time, another library for working with dates has surfaced and gained a lot of traction: https://date-fns.org/
这个库默认是不可变的,遵循模块化的功能架构,这意味着它更适合树摇动和客户端捆绑。如果您正在开发一个在客户端广泛使用Webpack的项目,并发现Moment.js给您的构建带来麻烦,或者即使Moment.js的可变性让您头疼,那么您应该尝试 date-fns
。
This library is immutable by default and follows a modular, functional architecture, which means it is better suited to tree shaking and client-side bundling. If you are working on a project that makes extensive use of Webpack on the client side, and find that Moment.js is giving you trouble with your build, or even if Moment.js' mutability is causing you a lot of headache, then you should give date-fns
a try.
这篇关于我如何在moment.js中解决可变性问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!