New JavaScript object instance unexpectedly retaining old array data

42 views Asked by At

I have a JavaScript object declared in code like:

ObjectClass = Class.extend({
    ...
    arrayProperty : [],
});

It gets instantiated with:

var gblObject;
...
gblObject = new ObjectClass();

gblObject.arrayProperty always gets an initial value written to is using gblObject.arrayProperty.push(defaultObject); and potentially gets more values written to it, but using gblObject.arrayProperty = [defaultObject, anotherObject, ..., nObjects]; Note: defaultObject is the same object that was added initially using push.

Eventually gblObject gets reset with gblObject = null;

The issue comes in when I try to use the same namespace gblObject = new ObjectClass();. When I do this, I can console log and see that gblObject.arrayProperty returns Array [ {defaultObject} ]. I expect this to be an empty array however, since it's a completely new instance of ObjectClass. The weird thing is gblObject looks empty in the console log: Object { }. But there's a <prototype> value on the empty object, and this contains that pesky arrayProperty : Array [ {defaultObject} ] assignment.

Why would the object property array value persist on new instances, but only the value that gets written using push?

I was able to workaround the persisting value by setting the initial array value with gblObject.propertyAsList = [defaultObject] instead of using push. Another solution was to do:

gblObject = new ObjectClass();
gblObject.arrayProperty = [];
...
gblObject.arrayProperty.push(defaultObject);

But I would still like to understand why this issue occurs.

0

There are 0 answers