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

I need to copy moment to a new variable without references.let momentDate= moment('2018-01-01�

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745660931a4638832.html

相关推荐

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

    I need to copy moment to a new variable without references.let momentDate= moment('2018-01-01�

    21天前
    60

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信