0

Reading the book "YDKJS" about 'mixins' (manually copying one object into another) I ran into that statement: There are still some subtle ways the two objects can affect each other even after copying, such as if they both share a reference to a common object (such as an array or function). So I need an example of this statement. When I tried to change the common object(reference to it) It didn't work, they don't affect each other.

function foo() {
  let array = [2, 2, 1];
  return array;
}

function mixin(sourceObj, targetObj) {
  for (let key in sourceObj) {
    if (!(key in targetObj)) {
      targetObj[key] = sourceObj[key];
    }
  }
  return targetObj;
}

const Vehicle = {
  engines: 1,
  fooo: foo,
  ignition: function () {
    console.log('Turning on my engine');
  },

  drive: function () {
    this.ignition();
    console.log('Steering and moving forward');
  }
};

const Car = mixin(Vehicle, {
  wheels: 4,

  drive: function () {
    console.log('Rolling on all ' + this.wheels + ' whells!');
  }
});



console.log(Vehicle.fooo());
console.log(Car.fooo());
Car.fooo = function () {
  let array = [34, 65, 1];
  return array;
};

console.log(Car.fooo());
console.log(Vehicle.fooo());
Rustem
  • 1
  • 1
  • 1
    Please show the code where you “tried to change the common object”. – Ry- Jan 08 '18 at 09:39
  • I added the code – Rustem Jan 08 '18 at 10:00
  • When you set `var a = {}; b = a;`, `b` and `a` contain the same object reference. When you set `b = 'hello'`, `a` doesn’t change, because you’re overwriting the reference and not changing what’s referenced. Same idea here. – Ry- Jan 08 '18 at 10:06

0 Answers0