0

I ran this code (found on https://gist.github.com/tomachalek/187fd3e18260ef04ad8a):

(function() {
  'use strict';

  var foo, bar1, bar2;

  function Foo() {
    this.counter = {
      i: 0
    };
    this.counter2 = 0;
  }

  function Bar() {}

  foo = new Foo();
  Bar.prototype = foo;

  Bar.prototype.sayHello = function() {
    console.log('sayHello(): counter1 =',
      this.counter.i,
      ', counter2 =',
      this.counter2,
      '\n');
    this.counter.i += 1;
    this.counter2 += 1;
  };

  bar1 = new Bar();
  bar2 = new Bar();

  foo.sayHello();
  bar1.sayHello();
  bar2.sayHello();
  foo.sayHello();
}());

and got this result:

sayHello(): counter1 = 0 , counter2 = 0 

sayHello(): counter1 = 1 , counter2 = 1 

sayHello(): counter1 = 2 , counter2 = 1 

sayHello(): counter1 = 3 , counter2 = 1 

Could somebody explain why the output is so? I expected both counter1 and counter2 to be increasing and identical.

Andy
  • 61,948
  • 13
  • 68
  • 95
blueblast
  • 87
  • 2
  • 10
  • 1
    Because there is only a single `{i: 0}` object (referenced from `foo.counter` and inherited as `bar1.counter` and `bar2.counter`), while each of the objects has its own `.counter2` property. – Bergi Sep 03 '21 at 23:16
  • @Bergi Is this pass by value vs. pass by reference? – blueblast Sep 04 '21 at 13:13
  • Not really, that terminology is only relevant for function calls. But yes, it is about shared references to objects. – Bergi Sep 04 '21 at 13:15

0 Answers0