Javascript 我如何解决 moment.js 中的可变性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30979178/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:01:26  来源:igfitidea点击:

How do I work around mutability in moment.js?

javascriptobjectimmutabilitymomentjsmutability

提问by Shengbo1618

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.

我遇到了一个问题,我必须存储一个 moment 对象的初始值,但是我在阻止我的变量与原始对象一起更改时遇到了一些麻烦。

Unfortunately Object.freeze() doesn't work, because moment.js returns an "Invalid date" error when I try to format that.

不幸的是 Object.freeze() 不起作用,因为当我尝试格式化时,moment.js 返回“无效日期”错误。

回答by razorbeard

There's a Moment.js plugin on NPM called frozen-moment- You could use moment().freeze()in place of Object.freeze(moment()).

有一个Moment.js插件上NPM称为冷冻时刻-你可以使用moment().freeze()代替Object.freeze(moment())

Otherwise, vanilla Moment.js has a clonemethod that should help you avoid mutability problems, so you could do something like this:

否则,vanilla Moment.js 有一个clone方法可以帮助您避免可变性问题,因此您可以执行以下操作:

var a = moment(),
    b = a.clone(); // or moment(a)

UPDATE:

更新:

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/

我写这个答案已经两年了。在这个时候,另一个处理日期的库已经浮出水面并获得了很多关注:https: //date-fns.org/

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-fnsa try.

默认情况下,该库是不可变的,并遵循模块化的功能架构,这意味着它更适合于摇树和客户端捆绑。如果你正在开发一个在客户端大量使用 Webpack 的项目,并且发现 Moment.js 给你的构建带来了麻烦,或者即使 Moment.js 的可变性让你很头疼,那么你应该date-fns试一试。

回答by spirytus

It's an old question and apologies for shameless self promotion as this is not my intention, just hope it will help someone.

这是一个老问题,为无耻的自我宣传道歉,因为这不是我的本意,只是希望它会帮助某人。

In addition to what razorbeard says (.clone()etc) I created NPM module that attaches immutable methods to whatever Moment.js comes with out of the box. The intention is not to break existing code so module adds new methods with Immuappended to its name.

除了 razorbeard 所说的(.clone()等)之外,我还创建了 NPM 模块,该模块将不可变方法附加到开箱即用的 Moment.js。目的不是破坏现有代码,因此模块添加了Immu附加到其名称的新方法。

Each instance returned by moment factory will be decorated with immutable methods e.g moment().startOf()will have corresponding startOfImmu(), add()will have addImmu()etc. Each of those returns new moment rather then modifying existing one. To use it just pass momentfactory to momentImmutableMethodsto get access to new immutable methods. Example:

时刻工厂返回的每个实例都将使用不可变方法进行修饰,例如,moment().startOf()将具有相应的startOfImmu()add()将拥有addImmu()等。这些方法中的每一个都返回新的时刻而不是修改现有的时刻。要使用它,只需通过momentfactory 即可momentImmutableMethods访问新的不可变方法。例子:

var moment = require('moment'); // or moment-timezone 
import { momentImmutableMethods } from 'moment-immutable-methods';

// to decorate instances with immutable methods we need to extend moment factory as below:
momentImmutableMethods(moment);

// now every instance returned by moment will have Immu methods attached.


// IMMUTABLE EXAMPLE
// we using immutable methods that were attached to every instance, these have Immu appended to original name
const ddd = moment({
  hour: 5,
  minute: 10
});
// Moment {_isAMomentObject: true, _i: {…}, _isUTC: false, _pf: {…}, _locale: Locale, …}
const eee = ddd.startOfImmu('day');
// Moment {_isAMomentObject: true, _i: {…}, _isUTC: false, _pf: {…}, _locale: Locale, …}
console.log(ddd === eee);
// false
const fff = eee.startOfImmu('month');
// Moment {_isAMomentObject: true, _i: {…}, _isUTC: false, _pf: {…}, _locale: Locale, …}
console.log(ddd === fff);
// false
console.log(eee === fff);
// false
console.log(ddd.format('DD/MM/YY HH:mma'));
// "14/04/18 05:10am"
console.log(eee.format('DD/MM/YY HH:mma'));
// "14/04/18 00:00am"
console.log(fff.format('DD/MM/YY HH:mma'));
// "08/04/18 00:00am"

Its on NPM at https://www.npmjs.com/package/moment-immutable-methods

它在 NPM 上https://www.npmjs.com/package/moment-immutable-methods