ExtJs Inheritance Inheritance

Can someone explain this behavior to me. Let's 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'); 

Check property

 a.setA(1); b.setA(2); a.sayA(); b.sayA(); 

Displays

 1 2 

All right but

 a.add(1); b.add(2); a.sayAr(); b.sayAr(); 

We get

 [1,2] [1,2] 

I do not understand this. Why does it use separate properties of "a", but one array of "ar" for both objects. "ar" is not declared static! I don’t understand at all.

+6
source share
2 answers

When you put something in a class declaration, it means that it falls on the prototype of the object (read: it becomes common to all instances). This is not a problem for strings / numbers / bools, but for objects and arrays you will see that this behavior takes effect.

If you want to have an array / object for each instance, then you need to explicitly add it to the instance:

 Ext.define('baseClass',{ a:null, constructor: function(){ this.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); } }); 
+8
source

What about this bit here:

 Ext.define('baseClass',{ a:null, ar:[], <--------------------------- you're instantiating an array object! 

To make it clearer, the above code is equivalent:

 Ext.define('baseClass',{ a:null, ar:new Array(), 

Thus, both objects have the same array, because the constructor of the object only copies the reference to the array, not the full array object.

You don’t know how Ext.js handles constructors / initializers, but you need to create an array during the construction of the object, and not when you declare it ....

Ok, Googling gave me this:

 Ext.define('baseClass',{ constructor: function () { this.ar = []; }, 

This should solve your problem.

+3
source

Source: https://habr.com/ru/post/922904/