Simple problems with JS replication

an object foo has a property baidu

var foo = {
    baidu:"woshibaidu"
    }

now there is an object boo that references foo

    var boo = foo

so at this point, adding or modifying attributes in boo will affect foo,. For example, this code will add an attribute to both foo and boo.

    boo.google = "imgoogle"

now there is a problem. The google attribute added by boo will appear in foo, and will also change in foo when boo is modified. How to make boo reference the value of Baidu in foo, but cannot modify the value of google in boo in foo

Mar.20,2021

it is not possible to define boo in this way:

var boo = foo

only by defining boo in this way can you achieve the effect you say:

var boo = {
    get baidu () {
        return foo.baidu
    },
    set baidu (val) {
        foo.baidu = val
    },
    google: 'imgoogle'
}


what you do directly is equivalent to making a shallow copy of an object . For an object, you point boo to the heap of foo (picture: foo and boo point to the same address), so whether you change foo or boo, you are changing the same thing. So if you just want the value in it, you should use to make a deep copy of :

`

var foo = {
    baidu:'woshibaidu'
}
var boo = JSON.parse(JSON.stringify(foo));
boo.baidu = "newBaidu"
boo.google = "imgoogle";

console.log(foo)    // {baidu: "woshibaidu"}
console.log(boo)    // {baidu: "newBaidu", google: "imgoogle"}

`

such a method can make a deep copy of an object, but one problem is that if there is a function call in your object, it will skip that display. So in that case, you can only use recursion to achieve a deep copy of an object


if you want to directly clone an object, completely independent, as follows:

function objClone(initalObj){
  var o = initalObj instanceof Array ? [] : {};
  for(var k in initalObj) {
    o[k] = (typeof(initalObj[k]) === 'object')&&(initalObj[k] != null) ? objClone(initalObj[k]) : initalObj[k];
  }
  return o;
}

var foo = {
  baidu:'woshibaidu'
};
var boo = objClone(foo);
boo.google = "imgoogle"; // foo.googleundefined
//fooboo

if you want to inherit an object, then modify it as follows

function deepPrototypeClone(obj) {
  const ret = Object.create(obj);
  for (const [key, value] of Object.entries(obj)) {
    if (value && typeof value === 'object') {
      ret[key] = deepPrototypeClone(value);
    }
  }
  return ret;
}

var foo = {
  baidu:'woshibaidu'
};
var boo = deepPrototypeClone(foo);
boo.google = "imgoogle"; // foo.googleundefinded
//boofoofooboofooboo
Menu