How to clone a javascript ES6 class instance

This question already has an answer here:

  • How do I correctly clone a JavaScript object? 54 answers

  • 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.

    链接地址: http://www.djcxy.com/p/24758.html

    上一篇: 将JavaScript对象推入数组中

    下一篇: 如何克隆一个JavaScript ES6类实例