Can someone please explain this behavior to me.
Lets declare a class:
Ext.define('baseClass',{
a:null,
ar:[],
add:function(v) {
this.ar.push(v);
},
sayAr:function() {
console.log(this.ar);
},
setA:function(v) {
this.a= v;
},
sayA:function() {
console.log(this.a);
}
});
Now I create two objects
var a = Ext.create('baseClass');
var b = Ext.create('baseClass');
Test the property
a.setA(1);
b.setA(2);
a.sayA();
b.sayA();
This outputs
1
2
Everything is OK, but
a.add(1);
b.add(2);
a.sayAr();
b.sayAr();
We get
[1,2]
[1,2]
This I don’t understand. Why does it use separate “a” properties but one “ar” array for both objects.
“ar” is not declared as static!
I don’t get it at all.
When you put something in the class declaration, it means it gets pushed onto the object prototype (read: it gets shared across all instances). It’s not really a problem for strings/numbers/bools, but for objects and arrays you’ll see this behaviour come in to effect.
If you want to have an array/object per instance, then you need to explicitly add it in the instance: