问题
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