View Full Version : Bug with statics and array type class members?

30 Mar 2012, 2:21 PM
I'm attempting to use a 'factory' pattern for generating new instances of a class, with the factory method contained in the 'statics' object. However, in classes with array type members, rather than each instance starting with an empty array as defined, each new instance shares a common array.

Simple variables (i.e. strings) do not behave this way.

For example:

//define class members:
stringVar: '',
arr: [],
obj: {},

//static factory:
createInstance: function(stringVar)
var newInstance = new this();
newInstance.stringVar += stringVar;
newInstance.arr[newInstance.arr.length] = "B";

Ext.onReady(function ()
var first = ClassA.createInstance('1');
alert("First's Arr:" + first.arr);
var second = ClassA.createInstance('2');
alert("Second's Arr:" + second.arr); //shows 'B,B'
alert("First Arr is now:" + first.arr); //also shows 'B,B'
alert("First string is still OK:" + first.stringVar + " vs " + second.stringVar);});

Is this in fact a bug, or are my expectations incorrect? I can get around it by adding a constructor that defines and sets initial values, but that seems like an odd workaround.



30 Mar 2012, 2:28 PM
Anything you declare on the class is shared between all instances. For 'primitive' type values it doesn't matter, but for objects & arrays they are all shared.

As you've suggested, you need to initialize one per instance if you don't want that to be the case.

30 Mar 2012, 2:37 PM
Evan -

Thanks for the reply. That being the case, what is the recommended way to have 'instance' variables?

One solution I found is defining them in the constructor.

I attempted briefly to use the config{} approach as in the docs, but did not have success with that using this factory approach.

Just looking for which pattern is considered 'best'.


30 Mar 2012, 2:51 PM
Yeah, just creating the new instance in the constructor/initComponent (if it's a component) is the way to go.

30 Mar 2012, 3:04 PM
much obliged, thank you.