0

Consider this example:

If you were to take the above code and run it, the console message would be 100. Why does it print out 100 when I added the 100 to the position in obj2's "this"? How do I make it so that obj2 has its own unique "this"? Also please know that is an simplified example of my code, I cannot just make a seperate object in obj2 which contains everything.

var obj1 = function() {
  this.obj2Arr = [];
  this.pos = {
    "x": 0,
    "y": 0
  };
  this.obj2Arr.push(new obj2(this.pos));
  console.log(this.pos.x);
  // Prints out 100 even though obj2 was where I added the 100 for it's "this".
  // Why does it do that, and how do I make obj2's "this" unique to it?
};

var obj2 = function(pos) {
  this.pos = pos;
  this.pos.x = this.pos.x + 100;
};

var example = new obj1();
console.log(example);
mplungjan
  • 169,008
  • 28
  • 173
  • 236
KingCoder11
  • 415
  • 4
  • 19
  • You have a reference to the same `obj pos` in memory, so you're modifying the same `pos` from `obj1`. – Ele Mar 10 '18 at 17:50
  • So how do I make the position to obj2 unique? – KingCoder11 Mar 10 '18 at 17:51
  • An alternative is using Spread syntax `new obj2({...this.pos})` or `new obj2(Object.assign({}, this.pos))` – Ele Mar 10 '18 at 17:52
  • 1
    @KingCoder11 You'll need to create a copy/clone of `pos`. That isn't automatic with objects. – [How do I correctly clone a JavaScript object?](https://stackoverflow.com/questions/728360/how-do-i-correctly-clone-a-javascript-object) – Jonathan Lonowski Mar 10 '18 at 17:54

1 Answers1

3

This is because pos is an object and objects are always passed by reference in javascript.

To answer your question: use Object.assign to create a fresh object:

var obj1 = function() {
  this.obj2Arr = [];
  this.pos = {
    "x": 0,
    "y": 0
  };
  this.obj2Arr.push(new obj2(Object.assign({}, this.pos)));
  console.log(this.pos.x);
};

var obj2 = function(pos) {
  this.pos = pos;
  this.pos.x = this.pos.x + 100;
};

var example = new obj1();
console.log(example);
Marco
  • 7,007
  • 2
  • 19
  • 49
  • Objects are a "reference type" that are passed by value so only the reference is copied. They're not actually passed "by reference". –  Mar 10 '18 at 17:56
  • This is only cloning the first level and not the entire object. You need to explain that. – Ele Mar 10 '18 at 17:57