1

I have a problem when I instantiate a class 2 times. The 2nd instance keep parameters of the first only if the objects.

Here is a simple example:

var Test = function() {};
Test.prototype = {
 bonjour: null,
 hello: {
  hum: null,
  ya: null,
 },
};

var testA = new Test();
testA.bonjour = 'Aaa';
testA.hello.hum = 'Bbb';
// return "Aaa"
console.log(testA.bonjour);
// return "{ hum: 'Bbb', ya: null }"
console.log(testA.hello);

console.log('');

var testB = new Test();
// return "null" -> ok
console.log(testB.bonjour);
// return "{ hum: 'Bbb', ya: null }" -> wtf ?!
console.log(testB.hello);

Does anyone have any idea why? Thank you.

SiteXw
  • 588
  • 1
  • 4
  • 14
  • Mutating prototype affects all instances using that prototype. More information about this can be found here: http://stackoverflow.com/a/16063711/1641941 – HMR Jan 20 '15 at 01:33

1 Answers1

4

The value of your "hello" property on the prototype is a reference to an object. Each constructed instance will have access to that reference, but there's only one object involved. Thus, changes made to that object via one instance will be visible from all others.

You can see this by adding

console.log(testA.hello === testB.hello); // will log "true"

If you want each instance to have it's own "hello" object, you'll have to assign the property in the constructor.

var Test = function() {
    this.hello = { hum: null, ya: null };
};
Pointy
  • 405,095
  • 59
  • 585
  • 614
  • Okk. In fact, it is completely logical, but instantly I was going crazy! ^^ Ty – SiteXw Jan 19 '15 at 20:46
  • Typically when you're using prototypes, you only want to define methods on the prototype. The assumption is that you will be changing values on each instance, but you won't be changing its methods. – Daniel Weiner Jan 19 '15 at 21:02