Nodejs: how to clone an object

后端 未结 12 2071
情书的邮戳
情书的邮戳 2020-12-04 18:32

If I clone an array, I use cloneArr = arr.slice()

I want to know how to clone an object in nodejs.

12条回答
  •  时光说笑
    2020-12-04 19:26

    Depending on what you want to do with your cloned object you can utilize the prototypal inheritence mechanism of javascript and achieve a somewhat cloned object through:

    var clonedObject = Object.create(originalObject);
    

    Just remember that this isn't a full clone - for better or worse.

    A good thing about that is that you actually haven't duplicated the object so the memory footprint will be low.

    Some tricky things to remember though about this method is that iteration of properties defined in the prototype chain sometimes works a bit different and the fact that any changes to the original object will affect the cloned object as well unless that property has been set on itself also.

提交回复
热议问题