How to clone a javascript ES6 class instance

帅比萌擦擦* 提交于 2019-12-18 10:18:17

问题


How do I clone a Javascript class instance using ES6.

I'm not interested in solutions based on jquery or $extend.

I've seen quite old discussions of object cloning that suggest that the problem is quite complicated, but with ES6 a very simple solution presents itself - I will put it below and see if people think it is satisfactory.

edit: it is being suggested that my question is a duplicate; I saw that answer but it is 7 years old and involves very complicated answers using pre-ES6 js. I'm suggesting that my question, which allows for ES6, has a dramatically simpler solution.


回答1:


let clone = Object.assign( Object.create( Object.getPrototypeOf(orig)), orig)

I tried a lot, in the end this worked for me.

It also avoids to set the prototype, because they say it slows down the code a lot.

And it's a one-liner!




回答2:


const clone = Object.assign( {}, instanceOfBlah );
Object.setPrototypeOf( clone, Blah.prototype );

Note the characteristics of Object.assign: it does a shallow copy and does not copy class methods.

If you want a deep copy or more control over the copy then there are the lodash clone functions.



来源:https://stackoverflow.com/questions/41474986/how-to-clone-a-javascript-es6-class-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!