How do I clone a JavaScript class instance?

后端 未结 6 1976
悲哀的现实
悲哀的现实 2020-11-29 08:50

How do I clone a JavaScript class instance?

I tried the normal jQuery extend, but that just returns a vanilla object. I have looked through many other answers on sta

6条回答
  •  一向
    一向 (楼主)
    2020-11-29 09:06

    This will create a copy of an object with the same prototype (class) and same own properties (including enumerability/writability/getters/setters etc):

    function clone(obj) {
      return Object.create(
        Object.getPrototypeOf(obj), 
        Object.getOwnPropertyDescriptors(obj) 
      );
    }
    

    (see here)

    It doesn't necessarily work well for builtin objects. For example Array.isArray(clone([])) is false, and clone(function () {})() says it is not a function, but for user created objects (either class instances or object literals) it works fine.

    To do a deep clone, you will have to loop over the property descriptors and clone the values recursively:

    function deepClone(obj) {
      if (obj === null || typeof obj !== "object")
        return obj
      var props = Object.getOwnPropertyDescriptors(obj)
      for (var prop in props) {
        props[prop].value = deepClone(props[prop].value)
      }
      return Object.create(
        Object.getPrototypeOf(obj), 
        props
      )
    }
    

提交回复
热议问题