How to clone a javascript ES6 class instance

♀尐吖头ヾ 提交于 2019-11-29 22:00:53
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!

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.

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