Javascript - How to clone an object?

前端 未结 8 1951
悲&欢浪女
悲&欢浪女 2021-02-18 22:28

I am confused. I create a copy from myObjOne, than i delete an entry from myObjOne and JS delete the entry in my copy(myObjTwo) too? But w

8条回答
  •  执念已碎
    2021-02-18 23:09

    Lots of advice on how to make a copy not only of the object and it's properties, but of all the objects referenced by its properties. Here's a version that clones the object without copying it and so that the clone inherits all properties added later except for those shadowed by own properties of the clone:

    var cloneOf = (function() {
      function F(){}
      return function(o) {
        F.prototype = o;
        return new F();
      }
    }());
    

    Some may recognise the pattern. An example:

    var base = {foo:'foo', bar:'bar'};
    var baseClone = cloneOf(base);
    alert(baseClone.foo);  // foo
    

提交回复
热议问题