IckyIckyInsects
IckyIckyInsects

Reputation: 23

Creating new object instance without overwriting the old one in JavaScript

I have a function with a prototype that contains both objects with variables/constants and other functions. One of these functions includes an initialization function to set the variables/constants inside the prototype. This works well (for my purposes) when only one instance of the object is created. However, when multiple instances are created, the old instance gets over-ridden instead of a purely "new" object being created.

As usual, this is best shown/explained in the coding sample below.

var objectTest = function () {};

objectTest.prototype = {
   _params: {
      a: ""
   },
   init: function (a){
       var self = this;
       self._params.a = a;
   }
};

var object1 = new objectTest();
object1.init("foo");
var object2 = new objectTest();
object2.init("bar")

$("#Testing").html(object1._params.a);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="Testing">Initial</div>

While I would expect object1._params.a to be "foo", it is instead "bar". How can I organize/modify this code so that object1._params.a is "foo" while object2._params.a is "bar"? I also have access to JQuery should the answer lie somewhere in using that.

Upvotes: 1

Views: 710

Answers (1)

Shimmy568
Shimmy568

Reputation: 503

The problem has to do with immutability. Since you create the _params object inside of the prototype it gets shared across all instances (since the prototype is shared across instances as well). The way to avoid this is to only create functions in the prototype and initialize the fields in the constructor instead.

var objectTest = function () {
    this._params = {
        a: ""
    };
};

objectTest.prototype = {
   init: function (a){
       var self = this;
       self._params.a = a;
   }
};

var object1 = new objectTest();
object1.init("foo");
var object2 = new objectTest();
object2.init("bar")

$("#Testing").html(object1._params.a);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="Testing">Initial</div>

Also try and use classes instead of messing around with prototypes manually, but I'm sure you have your reasons ;P.

Upvotes: 3

Related Questions