最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to do full copy from moment.js - Stack Overflow

programmeradmin1浏览0评论

I need to copy moment to a new variable without references.

let momentDate  = moment('2018-01-01', 'YYYY-MM-DD');

// I need to create a full clone of moment here
// Tried: 
// -- let copy = {...moment}   
// -- let copy = new(moment)   
// -- let copy = clone(moment) // 
// -- let copy = Object.assign({}, moment)
let momentCopy  = /*new*/ moment; 

momentCopy.fn.xFormat = function() {
    return this.format('[new-format-fn::]' + 'YYYY-MM-DD')
}

// expected Error:momentDate.xFormat is not a function
// but xFormat applied to momentDate
log(momentDate.xFormat()); 

log(momentCopy().xFormat())

Can anyone help me?

jsfiddle example

I need to copy moment to a new variable without references.

let momentDate  = moment('2018-01-01', 'YYYY-MM-DD');

// I need to create a full clone of moment here
// Tried: 
// -- let copy = {...moment}   
// -- let copy = new(moment)   
// -- let copy = clone(moment) // https://www.npmjs./package/clone
// -- let copy = Object.assign({}, moment)
let momentCopy  = /*new*/ moment; 

momentCopy.fn.xFormat = function() {
    return this.format('[new-format-fn::]' + 'YYYY-MM-DD')
}

// expected Error:momentDate.xFormat is not a function
// but xFormat applied to momentDate
log(momentDate.xFormat()); 

log(momentCopy().xFormat())

Can anyone help me?

jsfiddle example

Share Improve this question asked Jan 14, 2019 at 6:50 talkhabitalkhabi 2,7593 gold badges22 silver badges29 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 4

Use moment(Moment); to clone a moment object.

And moment.fn is moment prototype. If you want to add custom method to copied object, you can set as momentCopy.xFormat = function(){}

let momentDate  = moment('2018-01-01', 'YYYY-MM-DD');

let momentCopy  = moment(momentDate); 

momentCopy.xFormat = function() {
    return this.format('[new-format-fn::]' + 'YYYY-MM-DD')
}
console.log(momentCopy.xFormat())
<script src="https://cdnjs.cloudflare./ajax/libs/moment.js/2.22.2/moment.js"></script>

From the docs,

All moments are mutable. If you want a clone of a moment, you can do so implicitly or explicitly. Calling moment() on a moment will clone it.

So just provide it back to moment( momentObj )

Import "cloneDeep" from "Lodash" and then

let momentCopy  = cloneDeep(moment); 

should work for you.

发布评论

评论列表(0)

  1. 暂无评论