0
function Game() {
    this.player = new Component();
    this.renderer = new Renderer(this.player);
}
function Renderer(player) {
    this.player = player;
    this.player.number = 4;
}
var game = new Game();

Can I get a value of variable (4) "number" in that way: game.player.number?

Rajesh
  • 24,354
  • 5
  • 48
  • 79
daniel098
  • 99
  • 8
  • I think this may help to understand that http://dmitrysoshnikov.com/ecmascript/chapter-8-evaluation-strategy/ – llamerr Jul 15 '16 at 10:26
  • Yes. Objects are passed by references. So when you do, `this.player = player`, player's reference is assigned and not entire object is copied – Rajesh Jul 15 '16 at 10:26
  • @Rajesh So every change in object in one place is 'copied' to all places where this object occur? – daniel098 Jul 15 '16 at 10:36
  • No. When you assign an object to some key/variable, object's reference is copied and not entire object. So when you change something in object, since all other variable/keys are still pointing to same reference, even they will get updates. – Rajesh Jul 15 '16 at 10:44
  • If you wish to copy object and not reference, following link might help: http://stackoverflow.com/questions/728360/how-do-i-correctly-clone-a-javascript-object – Rajesh Jul 15 '16 at 10:46
  • @Rajesh Thank you very much. – daniel098 Jul 15 '16 at 10:51
  • @Rajesh I have one more question - Did that work in this way with arrays too? Arrays have a one reference in a program? – daniel098 Jul 16 '16 at 12:54
  • Yes. Ever arrays are objects so yes they will have same behavior. – Rajesh Jul 16 '16 at 13:00
  • @Rajesh And simple variables too? – daniel098 Jul 16 '16 at 13:28

1 Answers1

0

To answer your question, yes. You can edit the contents of an object and that will reflect in the original object, but if you try to overwrite an entire object (the reference of it), you can't.

You can view an example in this jsfiddle (select Run top left): https://jsfiddle.net/kcx61hye/34/

var player = {number:1};
var player2 = {number:2};
function Renderer(player) {
    this.player = player;
    this.player.number = 4;
}
function Renderer2(player) {
    this.player=player2;
}
document.write(player.number); //Outputs 1
Renderer(player);
document.write(player.number); //Outputs 4, so object is modified
Renderer(player2);
document.write(player.number); //outputs 4, so no modification
Xilis
  • 164
  • 1
  • 5