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.