Umakant Patil
Umakant Patil

Reputation: 2308

JavaScript object stores previous values even in new object

JavaScript really behaves weirdly in case of Objects. Although I'm not sure if it is the correct behaviour.

Inside a new Object(), I set some properties in the object. Next time when I do again new Object(), instead of default values I get values set in previous instance. Argh.

Below example explains the problem clearly

function testo() {}

testo.prototype = {
  obj: {
    what: {
      value: 5
    }
  },
  done: function () {
    console.log(this.obj.what.value);
    this.obj.what = {value: 10};
  }
};

var x = new testo();
x.done();
var y = new testo();
y.done();

The output of above code is:-

5
10

I was expecting it to be:-

5
5

Why? Because I'm creating new Class() and in the previous instance I had set the value using 'this', it is not static and default properties of all objects inside it should show up.

I have created above example as the demo. I'm facing this issue in my library. I know it has to do with objects are stored as the reference.

How should I proceed to get the expected output? Any thoughts?

Upvotes: 0

Views: 416

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386560

You could move the prototype property (which is for all instances the identical) to just a this object in the class.

function testo() {
    this.obj = { what: { value: 5 } };
}

testo.prototype = {
    done: function () {
        console.log(this.obj.what.value); this.obj.what = { value: 10 };
    }
};

var x = new testo();
x.done();

var y = new testo();
y.done();

Upvotes: 3

Related Questions