PDA

View Full Version : Class prototype gets changed unexpectedly



nagesh2020
30 Jul 2012, 1:26 AM
Ext.define('TestClass',
{
config:
{
arr: []
},
constructor: function(config)
{
this.initConfig(config);
}
});

var instA = Ext.create('TestClass',
{
arr: [1, 2, 3]
});

alert(TestClass.prototype.arr); // empty

instA.arr.push(4);
instA.arr.push(5);

alert(TestClass.prototype.arr); // still empty

var instB = Ext.create('TestClass', {});
instB.getArr().push(4);
instB.getArr().push(5);

alert(TestClass.prototype.arr); // has two members ??!!

In this code the first two alerts show no members, while the third alert shows two members.
Can't understand the behavior? How does the prototype gets changed?
Can someone please help on this...

Regards,
Nagesh Borate

nagesh2020
31 Jul 2012, 7:02 PM
Can somebody reply to this?

mankz
31 Jul 2012, 8:11 PM
You should not put 'complex' objects (arrays, objects, dates) on the prototype like this. In case A your 'instance' array overwrites the prototype one, so it is safe but case B uses the prototype array version which is then shared (not copied) by all instances. Assign a new copy of the array in the constructor to play it safe.

nagesh2020
1 Aug 2012, 6:39 AM
Thanks for the answer. Assigning array in the constructor, i will try out that approach.
I didn't take the approach earlier, bcoz then i wont have the generated getters and setter and i will have to add them myself.

Pardon me for my lack of understanding, but i am still not able to figure out, why

instA.arr.push(4); //updates the local(instance) copy of array
but
instA.getArr().push(4); //updates the prototype(global or shared) copy of array

instA.getArr() is supposed to be returning instA.arr ?

Regards,
Nagesh Borate